前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 590 N-ary Tree Postorder Traversal

LeetCode 590 N-ary Tree Postorder Traversal

作者头像
一份执着✘
发布2019-12-30 16:57:29
4490
发布2019-12-30 16:57:29
举报
文章被收录于专栏:赵俊的Java专栏赵俊的Java专栏

题意

给定一颗 N 叉树 的根节点,返回后序遍历后的数组.

例 :

代码语言:javascript
复制
给予树:
         1 
       / | \ 
      3  2  4
     / \ 
    5   6 
将其后序遍历返回: [5,6,3,2,4,1].

解法

和二叉树的中序遍历差不多,需要注意处理好子节点的顺序即可。

非递归解法:

代码语言:javascript
复制
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    public List<Integer> postorder(Node root) {
         List<Integer> list = new ArrayList<>();

        if (root == null) {
            return list;
        }

        Stack<Node> stack = new Stack<>();
        stack.push(root);

        while (!stack.isEmpty()) {
            Node node = stack.peek();
            List<Node> children = node.children;
            if (children != null && children.size() != 0) {
                for (int i = children.size() - 1; i >= 0; i--) {
                    stack.add(children.get(i));
                }
            } else {
                list.add(stack.pop().val);
            }
            node.children = new ArrayList<>();
        }

        return list;
    }
}

递归解法:

代码语言:javascript
复制
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val,List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
    
    List<Integer> list = new ArrayList<>();

    public List<Integer> postorder(Node root) {
        if (root == null) {
            return list;
        }
        
        for (Node child : root.children) {
            postorder(child);
        }
        
        list.add(root.val);
        
        return list;
    }
}

Runtime: 1 ms, faster than 100.00% of Java online submissions for N-ary Tree Postorder Traversal. Memory Usage: 48.2 MB, less than 40.66% of Java online submissions for N-ary Tree Postorder Traversal.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-04-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意
  • 解法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档