zoukankan      html  css  js  c++  java
  • 【leetcode】590. N-ary Tree Postorder Traversal

    Recurisve:

    /*
    // 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> order = {};
            if (root) {
                traversal(root, order);
            }
            
            return order;
        }
        
        void traversal(Node* root, vector<int> &order) {
            int num = root->children.size();
            for (int i = 0; i < num; i++) {
                traversal(root->children.at(i), order);
            }
            
            order.push_back(root->val);
        }
    };
    

      

    Iteratve:

    /*
    // 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> order = {};
            map<Node*, bool> visit;
            stack<Node*> nodeStack;
            if (root) {
                nodeStack.push(root);
            }
            
            while (!nodeStack.empty()) {
                Node* node = nodeStack.top();
                int num = node->children.size();
                if (num > 0 && visit.find(node) == visit.end()) {
                    for (int i = num - 1; i >= 0 ; i--) {
                        nodeStack.push(node->children.at(i));
                    }
                    visit[node] = true;
                } else {
                    order.push_back(node->val);
                    nodeStack.pop();
                }
            }
            
            return order;
        }
    };
    

      

  • 相关阅读:
    我的DBDA类文件
    登录时的验证码怎么写?
    phpcms 制作简单企业站的常用标签
    HTML 基础知识
    目标
    split函数的实现
    myString操作符重载
    cout中的执行顺序_a++和++a
    二叉树的层次遍历法
    树的前中序遍历_求后续遍历
  • 原文地址:https://www.cnblogs.com/AndrewGhost/p/10348451.html
Copyright © 2011-2022 走看看