码迷,mamicode.com
首页 > 其他好文 > 详细

(N叉树 递归) leetcode 590. N-ary Tree Postorder Traversal

时间:2019-04-26 19:30:13      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:http   c++   span   height   via   tree   link   class   init   

Given an n-ary tree, return the postorder traversal of its nodes‘ values.

For example, given a 3-ary tree:

 

技术图片

 

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

 

Note:

Recursive solution is trivial, could you do it iteratively?

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

leetcode589. N-ary Tree Preorder Traversal类似。用递归会简单些

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> postorder(Node* root) {
        vector<int> vec;
        helper(root,vec);
        return vec;
    }
    void helper(Node* root,vector<int> &vec){
        if(!root) return;
        for(Node *cur:root->children){
            helper(cur,vec);
        }
        vec.push_back(root->val);
    }
};

 

(N叉树 递归) leetcode 590. N-ary Tree Postorder Traversal

标签:http   c++   span   height   via   tree   link   class   init   

原文地址:https://www.cnblogs.com/Weixu-Liu/p/10776100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!