首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >33 N-ary Tree Postorder Traversal

33 N-ary Tree Postorder Traversal

作者头像
devi
发布2021-08-18 16:14:52
发布2021-08-18 16:14:52
3660
举报
文章被收录于专栏:搬砖记录搬砖记录

题目

Given an n-ary tree, return the postorder traversal of its nodes’ values.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

Follow up:

Recursive solution is trivial, could you do it iteratively?

Example 1:

Example 2:

Constraints:

代码语言:javascript
复制
The height of the n-ary tree is less than or equal to 1000
The total number of nodes is between [0, 10^4]
代码语言:javascript
复制
/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};
*/

分析

题意:n叉树的后序遍历

思路: 只需要利用遍历“最小元”的思想进行递归即可。

n叉树后序遍历的最小元:遍历其他节点–>遍历根节点 从题意可知,根节点是root,其他节点是root.children中的节点。 因此算法就是,先递归遍历root.children的所有节点,再遍历根节点

解答

代码语言:javascript
复制
class Solution {
	// 存放结果
    List<Integer> list = new ArrayList<>();
    public List<Integer> postorder(Node root) {
    	// 递归终点
        if (root == null)
            return list;
        // 递归遍历其他节点
        for(Node node: root.children)
            postorder(node);
        // 遍历根节点
        list.add(root.val);
        return list;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/02/26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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