从上往下打印二叉树

时间:2023-01-17 17:28:10

利用arraylist构造treenode的队列,将每个结点的值输出并将每个结点的左右子树依次入队。

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        TreeNode p = root;
        ArrayList<Integer> list = new ArrayList<>();
        if(p != null){
            ArrayList<TreeNode> queue = new ArrayList<>();
            queue.add(p);
            while(queue.size() != 0){
                p = queue.remove(0);
                list.add(p.val);
                if(p.left != null){
                    queue.add(p.left);
                }
                if(p.right != null){
                    queue.add(p.right);
                }
            }
        }
        return list;
    }
}