题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/**
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> arraylist = new ArrayList<Integer>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if(root==null)
return arraylist;
//将根节点pRoot入队列
queue.offer(root);
while(!queue.isEmpty()){
//只要队列不为空就执行下面的操作
//首先将当前节点出队列
TreeNode newtree = queue.poll();
//判断是否存在左右节点,并各自入队列
if(newtree.left!=null){
queue.offer(newtree.left);
}
if(newtree.right!=null){
queue.offer(newtree.right);
}
//将当前节点的值val添加进arraylist
arraylist.add(newtree.val);
}
return arraylist;
}
}
网友评论