Prove safety Offer: printing the binary tree from the top down (sequence traversal java version)

Title Description

Downward from the print out of each node of the binary tree, with the layer node from left to right printing.

Using queue characteristic FIFO

Create a queue, followed by adding left and right child nodes. When taken from the queue, it is equivalent to from left to right in each layer of the access node

import java.util.*;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<>();
        if(root==null)
            return list;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            root = queue.poll();
            if(root.left!=null){
                queue.offer(root.left);
            }
            if(root.right!=null){
                queue.offer(root.right);
            }
            list.add(root.val);
        }
        return list;
    }
}

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/93469853