-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path589-N叉树的前序遍历.cpp
More file actions
54 lines (52 loc) · 1.25 KB
/
589-N叉树的前序遍历.cpp
File metadata and controls
54 lines (52 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
/********************************
//递归法
vector<int> preorder(Node* root) {
vector<int> res;
if(root == NULL)
return res;
//根节点
res.push_back(root->val);
if(!root->children.empty()){
//依次访问子节点
for(auto chil : root->children){
vector<int> tmp = preorder(chil);
for(int i=0;i<tmp.size();i++)
res.push_back(tmp[i]);
}
}
return res;
}
********************************/
//迭代法
vector<int> preorder(Node* root) {
vector<int> res;
if(root == NULL)
return res;
stack<Node*> s;
s.push(root);
while(!s.empty()){
Node* curNode = s.top();
s.pop();
res.push_back(curNode->val);
int len = curNode->children.size();
for(int i=len-1;i>=0;i--)
s.push(curNode->children[i]);
}
return res;
}
};