Offer sixty prove safety: the binary multi-layer printed lines

Casual working

Printing the binary tree in layers from top to bottom, from left to right with the output layer node. Each layer output line

Thinking

Traversal sequence Yeah! ! !

Code

public class Solution {
    ArrayList<ArrayList<Integer> > Print(TreeNode root) {
    Queue<TreeNode> queue=new LinkedList<TreeNode>();
         ArrayList<ArrayList<Integer>> arrays=new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> array=new ArrayList<Integer>();
        if(root==null)return arrays;
        queue.offer(root);
       // array.add(root.val); 如何进行表示表示他们是在同一层 是个问题的关键所在 这一点想不出来啊有点 可以利用for循环来实现
           
        while(queue.size()!=0){
            int len=queue.size();
          
           
            for(int i=0;i<len;i++){
                 TreeNode temp=queue.poll();
            if(temp.left!=null){
                queue.add(temp.left);
            }
            if(temp.right!=null){
                queue.add(temp.right);
            }
                array.add(temp.val);
            }
            arrays.add(array);
             array=new ArrayList<Integer>();
        }
        return arrays;
    }
    
}
Published 84 original articles · won praise 53 · views 7384

Guess you like

Origin blog.csdn.net/weixin_44015043/article/details/105422504