题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
分类:二叉树
解法1:使用队列来进行层次遍历即可。
分类:二叉树
解法1:使用队列来进行层次遍历即可。
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> res = new ArrayList<Integer>();
if(root==null) return res;
ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode cur = queue.remove(0);
res.add(cur.val);
if(cur.left!=null){
queue.add(cur.left);
}
if(cur.right!=null){
queue.add(cur.right);
}
}
return res;
}
}