使用队列层次输出二叉树加粗样式,难度较低,需要注意:
- 判断root为空的情况
- 每次从队列中poll,分别判断左右子树是否为空。
- 队列的使用,
Queue
为接口,需要用ArrayList
实现,入队出队分别为add
与poll
。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
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<TreeNode>();
ArrayList<Integer> ans=new ArrayList<Integer> ();
if (root == null) return ans;
queue.add(root);
ans.add(root.val);
while(!queue.isEmpty()){
TreeNode p=queue.poll();
if (p.left!=null){
ans.add(p.left.val);
queue.add(p.left);
}
if (p.right!=null){
ans.add(p.right.val);
queue.add(p.right);
}
}
return ans;
}
}