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

    科技2022-07-13  139

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

    目录

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

    1526. N叉树的前序遍历

    描述

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

    样例 1:

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

    题解

    /** * 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 tree * @return: pre order of the tree */ public List<Integer> preorder(UndirectedGraphNode root) { // write your code here List<Integer> ret = new ArrayList<>(); if (root != null) { ret.add(root.label); if (root.neighbors != null) { for (UndirectedGraphNode c : root.neighbors) { List<Integer> cRet = preorder(c); ret.addAll(cRet); } } } return ret; } }

    原题链接点这里

    鸣谢

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

    Processed: 0.010, SQL: 8