Sword refers to Offer 32-I. Print binary tree from top to bottom---Queue

Sword Finger Offer 32-I. Print a binary tree from top to bottom

Usage of Queue : https://www.runoob.com/java/data-queue.html

Queue<String> queue = new LinkedList<String>();

//Add element

queue.offer("a");

System.out.println("poll="+queue.poll()); //Return the first element and delete it in the queue

System.out.println("element="+queue.element()); //Return the first element

System.out.println("peek="+queue.peek()); //returns the first element

ArrayList

Find the size of the collection list. size()

Add element list.add(xx)

Get the element at the specified position list.get(index)

class Solution {
    public int[] levelOrder(TreeNode root) {
        if(root==null)  return new int[0];
        Queue<TreeNode> q=new LinkedList<>();
        List<Integer> list=new ArrayList<>();
        q.add(root);
        while(!q.isEmpty()){
            TreeNode node=q.poll();
            list.add(node.val);
            if(node.left!=null) q.add(node.left);
            if(node.right!=null)    q.add(node.right);
        }
        int[] res=new int[list.size()];
        for(int i=0;i<list.size();i++){
            res[i]=list.get(i);
        }
        return res;
    }
}

 

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/108078172