题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
import java.util.*;
/**
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) {
if (root == null) {
return new ArrayList<Integer>();
}
ArrayList<Integer> arr = new ArrayList<Integer>();
TreeNode node = root;
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
list.add(root);
while (list.size() > 0) {
TreeNode n = list.removeFirst();
if(n.left!=null){
list.addLast(n.left);
}
if(n.right!=null){
list.addLast(n.right);
}
arr.add(n.val);
}
return arr;
}
}
形成队列,进来的出队列要把左右子树存入队列,实现广度优先