领扣LintCode算法问题答案-1525. N叉树的后序遍历

    科技2022-07-13  141

    领扣LintCode算法问题答案-1525. N叉树的后序遍历

    目录

    1525. N叉树的后序遍历描述样例 1: 题解鸣谢

    1525. N叉树的后序遍历

    描述

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

    样例 1:

    输入 : {1,3,2,4#2#3,5,6#4#5#6} 输出: [5,6,3,2,4,1] 说明: 这棵树如下所示(左侧的)

    题解

    /** * Definition for Undirected graph. * class UndirectedGraphNode { * int label; * List<UndirectedGraphNode> neighbors; * UndirectedGraphNode(int x) { * label = x; * neighbors = new ArrayList<UndirectedGraphNode>(); * } * } */ public class Solution { /** * @param root: the root of the tree * @return: post order of the tree */ public List<Integer> postorder(UndirectedGraphNode root) { // write your code here List<Integer> ret = new ArrayList<>(); if (root != null) { if (root.neighbors != null) { for (UndirectedGraphNode c : root.neighbors) { List<Integer> cRet = postorder(c); ret.addAll(cRet); } } ret.add(root.label); } return ret; } }

    原题链接点这里

    鸣谢

    非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

    Processed: 0.009, SQL: 8