JZ32 从上往下打印二叉树
题源 👉 从上往下打印二叉树_牛客题霸_牛客网 (nowcoder.com)
题目描述:
具体实现:
方法一:层次遍历,迭代法,用队列实现
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> ans = new ArrayList<>();
if(root == null) return ans;
Deque<TreeNode> d = new ArrayDeque<>();
d.addLast(root);
while(!d.isEmpty()){
TreeNode t = d.pollFirst();
ans.add(t.val);
if(t.left != null) d.addLast(t.left);
if(t.right != null) d.addLast(t.right);
}
return ans;
}
时间:O(n)
空间:O(n)