Given an n-ary tree, return the preorder traversal of its nodes' values.
For example, given a 3-ary tree:
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); } } };
转载于:https://www.cnblogs.com/Weixu-Liu/p/10776096.html
相关资源:JAVA上百实例源码以及开源项目