zoukankan      html  css  js  c++  java
  • [leetCode]590. N叉树的后序遍历

    题目

    https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/

    给定一个 N 叉树,返回其节点值的后序遍历。

    例如,给定一个 3叉树 :

    在这里插入图片描述

    返回其后序遍历: [5,6,3,2,4,1].

    递归

    class Solution {
        List<Integer> ans = new ArrayList();
    
        public List<Integer> postorder(Node root) {
            traversal(root);
            return ans;
        }
    
        private void traversal(Node node) {
            if (node == null)
                return;
            for (Node c : node.children) {
                traversal(c);
            }
            ans.add(node.val);
        }
    }
    

    迭代

    class Solution {
        List<Integer> ans = new ArrayList();
    
        public List<Integer> postorder(Node root) {
            if (root == null) return ans;
             LinkedList<Node> stack = new LinkedList<>();
             stack.push(root);
             while (!stack.isEmpty()) {
                Node node = stack.pop();
                if (node != null) {
                    stack.push(node);
                    stack.push(null);
                    for (int i = node.children.size() - 1; i >= 0; i--) { // 左后进所以左先出
                    if (node.children.get(i) != null) 
                        stack.push(node.children.get(i) );
                    }
                
                } else {
                    Node cur = stack.pop();
                    ans.add(cur.val);
                }
             }
            return ans;
        }
    
    }
    
  • 相关阅读:
    数据库表关联分析
    java异常信息分析
    版本问题
    项目
    EXCEL工具
    项目安全
    服务器环境
    vue公共
    Linux 文件权限
    nginx
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13907276.html
Copyright © 2011-2022 走看看