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

    科技2022-07-13  140

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

    目录

    1533. N叉树的层序遍历描述样例 1:样例 2: 题解鸣谢

    1533. N叉树的层序遍历

    描述

    给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。

    例如,给定一个 3叉树 : 返回其层序遍历:

    [ [1], [3,2,4], [5,6] ]

    The depth of the tree is at most 1000.The total number of nodes is at most 5000. 图模型说明: https://www.lintcode.com/help/graph

    样例 1:

    输入:{1,3,2,4#2#3,5,6#4#5#6} 输出:[[1],[3,2,4],[5,6]] 解释:如上图

    样例 2:

    输入:{1,3,2#2#3} 输出:[[1],[3,2]] 解释: 1 / \ 3 2

    题解

    public class Solution { public List<List<Integer>> levelOrder(ArrayList<DirectedGraphNode> nodes) { List<List<Integer>> ret = new ArrayList<>(); if (nodes != null && nodes.size() > 0) { List<Integer> levelRet = new ArrayList<>(); ArrayList<DirectedGraphNode> cn = new ArrayList<>(); for (DirectedGraphNode n : nodes) { levelRet.add(n.label); if (n.neighbors != null) { cn.addAll(n.neighbors); } } List<List<Integer>> childRet = levelOrder(cn); for (List<Integer> child : childRet) { levelRet.removeAll(child); } ret.add(levelRet); ret.addAll(childRet); } return ret; } }

    原题链接点这里

    鸣谢

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

    Processed: 0.014, SQL: 8