给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树
:
返回其前序遍历: [1,3,5,6,2,4]
。
说明: 递归法很简单,你可以使用迭代法完成此题吗?
/*
// 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;
helper(root, res);
return res;
}
void helper(Node* node, vector<int>& res) {
if (!node) return;
res.push_back(node->val);
for (Node* child : node->children) {
helper(child, res);
}
}
};
class Solution {
public:
vector<int> preorder(Node* root) {
if (!root) return {};
vector<int> res;
stack<Node*> st{{root}};
while (!st.empty()) {
Node* t = st.top(); st.pop();
res.push_back(t->val);
for (int i = (int)t->children.size() - 1; i >= 0; --i) {
st.push(t->children[i]);
}
}
return res;
}
};