问题描述:
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
问题分析:
根据问题的描述,可以很明确的知道,问题是要求我们进行二叉树的层序遍历,只需要借助队列的先进先出的特点,就ok了。
注意:
编代码最初级的目的只是实现目的,而随着我们代码量的增加,目的变得不那么简单,我们要想方设法加快代码的执行速度,当然是在代码的性能上面。比如减少循环的次数等等。有两个因素:时间复杂度和空间复杂度,因为java虚拟机的存在,程序员不用为释放内存而烦恼,有时甚至是牺牲空间来减少时间,就是为了加快程序的运行。
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) {
// if(root==null){
// return new ArrayList<Integer>();//注意如果写return null,则会发生空指针异常,返回值是ArrayList<Integer>类型
//返回null,没有分配空间,所以会发生空指针异常
//}
ArrayList<Integer> list = new ArrayList<>();
if(root==null){
return list;
}
ArrayList<TreeNode> nodelist = new ArrayList<>();//相当于是队列,把节点信息放在里面
TreeNode current = root;
int index = 0;
nodelist.add(current);
list.add(current.val);
while(current!=null){ //只需要一遍的遍历二叉树
if(current.left!=null){
nodelist.add(current.left);
list.add(current.left.val);
}
if(current.right!=null){
nodelist.add(current.right);
list.add(current.right.val);
}
index++;
if(index<nodelist.size()){
current = nodelist.get(index);
}else{
break;
}
}
return list;
}
}