(N叉树 递归) leetcode589. N-ary Tree Preorder Traversal

Given an n-ary tree, return the preorder traversal of its nodes' values.

For example, given a 3-ary tree:

(N叉树 递归) leetcode589. N-ary Tree Preorder Traversal

Return its preorder traversal as: [1,3,5,6,2,4].

Note:

Recursive solution is trivial, could you do it iteratively?

---------------------------------------------------------------------------------------------------------------------------------

额,这个迭代不会,不过,如果会了二叉树的前序遍历的递归解法的话,解这个题就会感觉简单了,同理,后序遍历也是,不过,中序遍历上可能会很难写。

C++代码:

/*
// 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 *root,vector<int> &res){
if(!root) return;
res.push_back(root->val);
for(Node* cur : root->children){
helper(cur,res);
}
}
};
上一篇:【推荐】2022年十四五规划研究报告白皮书政策解读行业分析高质量发展指南(持续更新中)


下一篇:oc语言--BLOCK和协议