0%

589.N叉树的前序遍历

相关

  1. 二叉树的前序遍历:144
  2. 二叉树的中序遍历:94
  3. 二叉树的后序遍历:145
  4. N叉树的后序遍历:590

1. 递归

跟二叉树一样,时间O(n),空间O(n)

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
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;

Node() {}

Node(int _val) {
val = _val;
}

Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/

class Solution {
public:
vector<int> preorder(Node* root) {
if (root == nullptr)
return {};

vector<int> ans;
ans.push_back(root->val);
for (int i = 0; i < root->children.size(); i++) {
vector<int> subArray = preorder(root->children[i]);
ans.insert(ans.end(), subArray.begin(), subArray.end());
}

return ans;
}
};

2. 迭代

仿照二叉树的前序遍历的迭代实现方式。
访问根节点 -> 将右部分的节点按照从右往左的顺序入栈 -> 左节点入栈 ->
同样,我们还是可以将左节点入栈出栈的部分省去。
时间O(n),空间O(n).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> preorder(Node* root) {
stack<Node*> st;
vector<int> ans;
while (!st.empty() || root != nullptr) {
if (root == nullptr) {
root = st.top();
st.pop();
}
ans.push_back(root->val);
for (int i = root->children.size() - 1; i > 0; i--)
st.push(root->children[i]);
root = root->children.empty() ? nullptr : root->children[0];
}

return ans;
}
};