從上往下打印數組

題目描述: 從上往下打印出二叉樹的每個節點,同層節點從左至右打印(二叉樹層次遍歷)

public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        if(root == null)
            return res;
        //Queue is abstract; 不能用 new Queue<TreeNode>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            while(queue.size()!=0){
               root=queue.remove();
                 res.add(root.val);
                if(root.left!=null){
                    queue.add(root.left);
                }
                if(root.right!=null){
                    queue.add(root.right);
                }
        }
        return res;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章