题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路
题意其实就是二叉树的层次遍历,用队列来实现
public ArrayList<Integer> PrintFromTopToBottom2(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
ArrayList<TreeNode> helpList = null; //辅助队列
TreeNode tmp = null;
if(root == null){
return result;
}else{
helpList = new ArrayList<TreeNode>();
helpList.add(root);
while (!helpList.isEmpty()){
//队列不为空,证明有结点没遍历完
tmp = helpList.remove(0);//取出队首
result.add(tmp.val);
if(tmp.left != null)
helpList.add(tmp.left);
if(tmp.right != null)
helpList.add(tmp.right);
}
return result;
}
}