题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
import java.util.*;
import java.util.ArrayList;
/**
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) {
ArrayList<Integer> rest = new ArrayList<>();
Queue<TreeNode> que = new ArrayDeque<TreeNode>();
if(root == null){
return rest;
}
//传入的链表存储
que.offer(root);
while(!que.isEmpty()){
TreeNode cur = que.poll();
rest.add(cur.val);
//若是左右孩子存在,则存入左右孩子作为下一个层次
if(cur.left != null){
que.add(cur.left);
}
if(cur.right != null){
que.add(cur.right);
}
}
return rest;
}
}

百度公司氛围 562人发布