Sword refers to offer to brush questions-GZ22-print binary tree from top to bottom

Insert picture description here
Problem-solving ideas:
Insert picture description here
Through the analysis of the above specific examples, we can find the rule: every time a node is printed, if the node has child nodes, the child nodes of the node are placed at the end of a queue. Next, take the first node that entered the queue from the head of the queue and put it in the ArrayList, repeat the previous operation, until all the nodes in the queue are stored in the ArrayList.
Note:
In Java, Queue is an interface at the same level as List and Map . LinkedList also implements the Queue interface. The main functions in this interface are: when the
capacity is insufficient or the queue is empty, an exception will not be thrown: offer (add tail element ), peek (access the head element), poll (access the head element and remove)
throw an exception when the capacity is not enough or the queue is empty: add, element (access the queue element), remove (access the head element and remove)

import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/**
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 中,
        重复前面的操作,直至队列中所有的节点都存到ArrayList中。
        */
        //result用来保存输出的节点
        ArrayList<Integer> result = new ArrayList();
        if(root == null){
    
    
            return result;//注意:空树返回一个默认构造的空LinkedList,而不是一个空指针null
        }
        //用队列来存储曾经访问过,但仍有用的节点
        //注意Queue是接口,不能直接new
        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);
        //只要队列中还有节点就说明还没遍历完,继续。
        //每次从队列出队,然后将这个节点左右子入队列(FIFO,故能完成广度/层级遍历),
        //再将这个节点记录在result中即可。
        while(!queue.isEmpty()){
    
    
            TreeNode temp = queue.poll();
            result.add(temp.val);
            if(temp.left != null){
    
    
                queue.offer(temp.left);
            }
            if(temp.right != null){
    
    
                queue.offer(temp.right);
            }
        }
        return result;
        
    }
}

Guess you like

Origin blog.csdn.net/weixin_42118981/article/details/113100998