【树】589. N叉树的前序遍历

题目:

【树】589. N叉树的前序遍历

 

 

解法:

方法一:递归

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4 public:
 5     int val;
 6     vector<Node*> children;
 7 
 8     Node() {}
 9 
10     Node(int _val) {
11         val = _val;
12     }
13 
14     Node(int _val, vector<Node*> _children) {
15         val = _val;
16         children = _children;
17     }
18 };
19 */
20 
21 class Solution {
22 public:
23 
24     // 第一种:递归  (这个和二叉树遍历一个道理,只是left right 用vector遍历下就行)
25     vector<int> preorder(Node* root) 
26     {
27         vector<int> ve;
28         if (!root) 
29         {
30             return ve;
31         }
32         recursivePerorder(root, ve);
33         return ve;
34     }
35 
36     void recursivePerorder(Node* node, vector<int>& ve) 
37     {
38         if (!node) 
39         {
40             return;
41         }
42         
43         ve.emplace_back(node->val);
44 
45         int size = node->children.size();
46 
47         for (int i=0; i<size; i++ ) 
48         {
49             Node *n = node->children[i];
50             if (n) 
51             {
52                 recursivePerorder(n,ve);
53             }
54         }
55     }
56 };

 

方法二:迭代

 1 /*
 2 // Definition for a Node.
 3 class Node {
 4 public:
 5     int val;
 6     vector<Node*> children;
 7 
 8     Node() {}
 9 
10     Node(int _val) {
11         val = _val;
12     }
13 
14     Node(int _val, vector<Node*> _children) {
15         val = _val;
16         children = _children;
17     }
18 };
19 */
20 
21 class Solution {
22 public:
23     // 第二种:迭代
24      vector<int> preorder(Node* root) 
25      {
26         vector<int> ve;
27         if (!root) 
28         {
29             return ve;
30         }
31        
32        stack<Node*> st;
33        st.push(root);
34        while(!st.empty()) 
35        {
36            Node *node = st.top();
37            st.pop();
38 
39             if (node) 
40             {
41                 ve.emplace_back(node->val);
42             }
43             else 
44             {
45                 continue;
46             }
47 
48             if (!node->children.empty()) 
49             {
50                 int size = node->children.size();
51                 for (int i=size-1; i>=0; i--) 
52                 { 
53                     // 注意:这里要倒序 stack LIFO
54                     Node *n = node->children[i];
55                     if (n) 
56                     {
57                         st.push(n);
58                     }
59                 }
60             }
61        }
62 
63         return ve;
64     }
65 
66 };

 

上一篇:U盘安装Proxmox VE(一)


下一篇:Yangk's 静态主席树-模板