题解 | #从上往下打印二叉树#
从上往下打印二叉树
http://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) {
Queue<TreeNode> queue = new LinkedList<>();
ArrayList<Integer> we = new ArrayList<>();
if(root == null){
return we;
}
queue.offer(root);
while(!queue.isEmpty()){
root = queue.poll();
we.add(root.val);
if(root.left!=null){
queue.offer(root.left);
}
if(root.right !=null){
queue.offer(root.right);
}
}
return we;
}
}