Leetcode102. Hierarchical traversal of binary tree

Title description

Give you a binary tree, please return the node value obtained by traversing it in order. (That is, visit all nodes layer by layer, from left to right).

Example:
Binary tree:[3,9,20,null,null,15,7],

   3
   / \
  9  20
    /  \
   15   7

Return the traversal result of its hierarchy:


[
  [3],
  [9,20],
  [15,7]
]

answer

 public  List<List<Integer>>   levelOrder(TreeNode root) {
    
    
        if (root==null){
    
    
            return new ArrayList<>();
        }
        /*创建一个存储每层元素的一个数组*/
        List<List<Integer>> list=  new ArrayList<>();
        Queue<TreeNode> queue=new LinkedList<>();
        TreeNode node=root;
        queue.add(node);
        int count=0;
        /*如果队列非空则一直循环*/
        while(!queue.isEmpty()){
    
    
            /*记录当前层的节点信息*/
            LinkedList<Integer> temp = new LinkedList<>();
            count=queue.size();
            /*count用来判断当前层的节点有没有变空*/
            while (count>0){
    
    
                /*队首元素出队列*/
                node=queue.poll();
                temp.add(node.val);
                if (node.left!=null){
    
    
                    queue.add(node.left);
                }
                if (node.right!=null){
    
    
                    queue.add(node.right);
                }
                count--;
            }
            list.add(temp);
        }
        return list;
    }

Insert picture description here

Guess you like

Origin blog.csdn.net/pjh88/article/details/114682444