LeetCode429-N叉树的层次遍历(队列)

层次遍历,就是队列

队列其实就能解决最基本的顺序问题了

先把最先的放进去,然后遍历每个结点,再把他的子结点放进去,顺序就OK了,这是官方用法。

 

接下来就是解决层级问题,怎么确定每一层呢?

用current来计算当前要处理的结点

用child来计算这一层的结点带来的child结点的个数。

 

每当current处理完,就到下一层,把child的值附上去。

 

结束条件,每次遇到null就跳过,然后队列里面为0就算结束了

 

public class LeetCode429 {

    //多x树
    static class Node {
        public int val;
        //孩子是一个list
        public List<Node> children;

        public Node() {}

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

    public static void main(String[] args) {



    }

    public List<List<Integer>> levelOrder(Node root) {

        if(root==null)
            return new LinkedList<>();


        LinkedList<Node> queue = new LinkedList<>();

        List<List<Integer>> result = new LinkedList<>();



        int current = 1;
        int child = 0;
        //层级
        int level = 0;


        //第一个先创建好
        result.add(new LinkedList<>());
        queue.addLast(root);





        //队列里没有值,可以退出了
        while (queue.size()>0){
            //拿出当前的
            Node node = queue.pollFirst();

            if(node==null)
                continue;

            //数值放进list里
            result.get(level).add(node.val);

            //把他的孩子加到队列末尾
            for(int i=0,len=node.children.size();i<len;i++){
                queue.addLast(node.children.get(i));
            }

            //当前要操作的数--,操作成功才--,因为这个是记录这非null的
            current--;
            //下一次要操作的数就是孩子的数量相加
            child += node.children.size();

            //这一层刚好操作完了
            if(current==0){
                //多加一个数组
                result.add(new LinkedList<>());
                //level提高
                level++;
                //处理子孩子
                current=child;
                child=0;
            }



        }

        //要去掉最后一个,因为总会导致最后一个为[]
        result.remove(result.size()-1);

        return result;


    }

}

 

转载于:https://www.cnblogs.com/weizhibin1996/p/9756436.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值