[Print] Java interview questions binary tree from the top down

[Title]:
print out from the top of each node of the binary tree, with the layer node from left to right printing.

[Thinking]:
required order of the title is: 根、左、右.
willtreeNode storesqueueIn accordance with the queue 先入先出characteristic, the controlling queueThe order of the columnsIt can be.

[Key]: queues, trees

【Java】:

import java.util.ArrayList;
import java.util.LinkedList;//链表
import java.util.Queue;//队列
/**
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> arrayList = new ArrayList<Integer>();
        if (root==null){
            return arrayList;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();//队列:先入先出
        //将树存入队列中,按要求从上到下,从左到右添加到队列中:根、左子、右子
        queue.offer(root);//根:add()和remove()方法在失败的时候会抛出异常(不推荐),offer代替
        while (!queue.isEmpty()){
            TreeNode node= queue.poll();//树当前节点更新;poll()返回第一个元素,并在队列中删除
            arrayList.add(node.val);//保存当前节点
            if (node.left!=null){
                queue.offer(node.left);//左
            }
            if (node.right!=null){
                queue.offer(node.right);//右
            }
        }
        return arrayList;
    }
}

He published 195 original articles · won praise 335 · views 120 000 +

Guess you like

Origin blog.csdn.net/cungudafa/article/details/102605014