429. N叉树的层序遍历

题目

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

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

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

分析

此题有两种解法:
第一种仍然是像遍历二叉树一样遍历,但是要注意的是,这里是N叉树,所以需要两个队列.
第二种则是使用递归方式,效率更高一下

代码

解法1:

 /**
     * 土鳖做法:用父子队列来做,效率很低
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        Queue<Node> parentQueue = new LinkedList<>();
        Queue<Node> sonQueue = new LinkedList<>();
        parentQueue.offer(root);

        int index = 0;
        while (!parentQueue.isEmpty()) {
            Node cur = parentQueue.poll();

            while(result.size()<index+1){
                result.add(new ArrayList<Integer>());
            }
            result.get(index);
            List<Node> childrens = cur.children;
            for (Node children : childrens) {
                sonQueue.offer(children);
            }
            if (parentQueue.isEmpty()) {
                if (!sonQueue.isEmpty()) {
                    parentQueue = null;
                    parentQueue = sonQueue;
                    sonQueue = new LinkedList<>();
                    index++;
                }
            }
        }
        return result;
    }

解法2:

    /**
     * 递归方式
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder2(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        levelOrder(root,0,result);
        return result;
    }


    private void levelOrder(Node node,int depth,List<List<Integer>> result){
        if(node == null){
            return;
        }

        if(depth+1>result.size()){
            result.add(new ArrayList<>());
        }
        result.get(depth).add(node.val);


        for (Node child : node.children) {
            levelOrder(child,depth+1,result);
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值