给定一个N叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树
:
返回其前序遍历: [1,3,5,6,2,4]
。
说明: 递归法很简单,你可以使用迭代法完成此题吗?
思路:这道题就是n叉树的前序遍历,我们分为递归版和迭代版。
递归版:这种方法很简单,因为是前序遍历(根—左—右),所以每次先把当前节点放入res中,然后递归调用从左到右的节点即可。
参考代码:
/*
// 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:
void preorderHelper(Node* root, vector<int> &res) {
res.push_back(root->val);
for (int i = 0; i < root->children.size(); i++) {
if (root->children[i]) preorderHelper(root->children[i], res);
}
}
vector<int> preorder(Node* root) {
vector<int> res;
if (root == nullptr) return res;
preorderHelper(root, res);
return res;
}
};
迭代版:我们可以通过一个例子来看下:
我们通过一个例子来看如何通过栈来模拟前序遍历:
我们有如下的树结构:
1
/ \
2 3
/ \ / \
4 5 6 7
正确的前序遍历应该长这样:
1 2 4 5 3 6 7
我们使用一个栈来模拟这个过程:
- 把1放入栈。
- 把1出栈并加到结果中; 把1的孩子放到栈中。栈中的数变成 3, 2 并且 2 在栈顶;
- 把 2 出栈并加到结果中; 把2的孩子放到栈中. 所以栈中的元素变成 3, 5, 4 且 4 是栈顶元素。
- 把4和5出栈因为他们都是叶子结点,现在结果是 1, 2, 4, 5。
- 把 3出栈并把他的孩子加到栈中。 栈中的元素变成 7, 6 且 6 在栈顶。
- 把 6 和7 出栈,这时候栈变空,所以最后的结果是: 1, 2, 4, 5, 3, 6, 7
参考代码:
/*
// 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) {
stack<Node*> s;
vector<int> res;
if (root == nullptr) return res;
s.push(root);
while (!s.empty()) {
vector<Node*> children = s.top()->children;
res.push_back(s.top()->val);
s.pop();
for (int i = (children.size()-1); i >= 0; i--) {
s.push(children[i]);
}
}
return res;
}
};