Title: Print binary tree from top to bottom layer, same layer node from left to right output. Each layer outputs one line. The algorithm for address

I feel can oneself do first, you say !!!!!!

Their thinking

This problem is obviously a tree sequence traversal problem, which requires traversal of queue auxiliary data. Let’s start with a binary tree

For example, 🌰

Simulate the process: Insert F output F, insert child nodes CE output C, introns output node AD E, insert child nodes HG output A, no children, do not insert the output D, introns output node B H, no children, do not insert the output G, introns output node M B, no children, do not insert the output M, no children, This completes output without inserting, FCEADHGBM

code

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        // Secondary queue
         ArrayList<TreeNode> a = new ArrayList<>();
         ArrayList<Integer> result = new ArrayList<>();
        if(root == null) {return result;
        }
        a.add(root);
        while(a.size() ! =0){
            TreeNode node = a.get(0);
            if(node.left! =null){
                a.add(node.left);
            }
            if(node.right! =null){
                a.add(node.right);
            }
            result.add(node.val);
            a.remove(node);
        }
        returnresult; }}Copy the code