题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
递归思路
public class Solution {
ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
if(root==null){
return list;
}
list.add(root.val);
print(root);
return list;
}
private void print(TreeNode root){
if(root!=null){
if(root.left!=null){
list.add(root.left.val);
}
if(root.right!=null){
list.add(root.right.val);
}
print(root.left);
print(root.right);
}
}
}
非递归思路
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
if(root == null) return list;
queue.add(root);
while(queue.size() != 0) {
TreeNode temp = queue.remove(0);
if(temp.left != null) queue.add(temp.left);
if(temp.right != null) queue.add(temp.right);
list.add(temp.val);
}
return list;
}
}