• [LeetCode] 590. N-ary Tree Postorder Traversal


    Easy

    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?

    题目大意:对n-ary树后序遍历。尝试递归和迭代两种方法。

    后序遍历是左->右->根

    方法一:递归

    将子树当做一个节点,对子树递归调用函数的结果作为根节点的子节点,并按序合并入结果数组中。

    代码如下:

    class Solution {
    public:
        vector<int> postorder(Node* root) {
            if(!root)return {};
            vector<int> res;
            
            if(!root->children.empty()){
                vector<Node*>temp=root->children;
                for(int i=0;i<temp.size();++i){
                    vector<int> t=postorder(temp[i]);
                    res.insert(res.end(),t.begin(),t.end());
                }
            }
            res.push_back(root->val);
            return res;
        }
    };

    方法二:迭代

     将数据按照遍历的逆顺序放入堆栈中,然后再依次取出遍历那个节点的孩子节点,直到全部节点遍历。

    代码如下:

    class Solution {
    public:
        vector<int> postorder(Node* root) {
            if(!root)return {};
            vector<int> res;
            stack<Node*> s{{root}};
            while(!s.empty()){
                Node* temp = s.top();
                s.pop();
                res.insert(res.begin(),temp->val);
                if(!temp->children.empty()){
                    vector<Node*> t=temp->children;
                    for(int i=0;i<t.size();++i){
                        s.push(t[i]);
                    }
                }
            }
            return res;
        }
    };
  • 相关阅读:
    汉语6级试卷(转)
    看《第一滴血4》
    又爱又恨奥沙利文
    最爱“剁椒鱼头”
    中国移动用户请注意长途电话包有陷阱
    推荐一个免费原版KTV / MTV下载网站
    传说中的人品问题
    信息更改致乒乓球爱好者
    贴几张我家乐乐的照片
    Web Parts: From SharePoint to ASP.NET 2.0
  • 原文地址:https://www.cnblogs.com/cff2121/p/11549079.html
Copyright © 2020-2023  润新知