zoukankan      html  css  js  c++  java
  • LeetCode 590 N叉树的后序遍历

    题目链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/

    方法一递归法:先访问子节点,然后访问根。LeetCode代码:

    /*
    // Definition for a Node.
    class Node {
    public:
        int val;
        vector<Node*> children;
    
        Node() {}
    
        Node(int _val) {
            val = _val;
        }
    
        Node(int _val, vector<Node*> _children) {
            val = _val;
            children = _children;
        }
    };
    */
    
    class Solution {
    public:
        vector<int>res;
        vector<int> postorder(Node* root) {
            if(root){
                int len=root->children.size();
                for(int i=0;i<len;++i){
                    postorder(root->children[i]);
                }
                res.push_back(root->val);
            }
            return res;
        }
    };

    方法二:迭代法,思想类似于二叉树后续遍历的迭代法,将后序遍历转换类似前序遍历的遍历,与前序遍历不同的是是先访问根然后迭代访问根最右边节点,然后为右边的左边的一个节点,一直到访问完

    最左边节点为止。然后反向输出,类似于二叉树的后序遍历的迭代法。二叉树的后序遍历可参考https://www.cnblogs.com/zzw-/p/13296052.html 。 此题 LeetCode代码如下:

    vector<int>res;
            if(!root){
                return res;
            }
            stack<Node*>S;
            S.push(root);
            int len;
            while(!S.empty()){
               root=S.top();
               res.push_back(root->val); 
               S.pop();
               len=root->children.size();
               for(int i=0;i<len;++i){
                   S.push(root->children[i]);
               }
               
            }
            len=res.size();
           
            int temp;
            for(int i=0;i<len/2;++i){
                temp=res[i];
                res[i]=res[len-i-1];
                res[len-i-1]=temp;
            }
            return res;
        }
  • 相关阅读:
    接口分类
    HTTPS和HTTP的主要区别
    协议类
    小程序
    Polyfill
    去重数组
    odoo 接口跨域请求报错
    docker-compose 自定义容器名称
    linux ssh 防暴力破解fail2ban
    odoo 知识点
  • 原文地址:https://www.cnblogs.com/zzw-/p/13324545.html
Copyright © 2011-2022 走看看