Print the binary tree from top to bottom

Question: Print each node of the binary tree from top to bottom, and print the nodes at the same level from left to right.

Given tree node structure:

public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
    }
 
}

 The level traversal of the binary tree is implemented with the help of a queue.

code show as below:

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> arrayList = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
 
        if (root != null) queue.offer(root);
 
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            arrayList.add(node.val);
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
 
        return arrayList;
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324590487&siteId=291194637