欢迎来到PJCK的博客

(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:

 

 

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);
        }
    }
};

 

posted @ 2019-04-26 19:12  PJCK  阅读(148)  评论(0编辑  收藏  举报