题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
import java.util.ArrayList;
import java.util.*;
/**
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) {
Queue<TreeNode> queue = new LinkedList<>();
ArrayList<Integer> list = new ArrayList<>();
PrintFromTopToBottom(root,list,queue);
return list;
}
public void PrintFromTopToBottom(TreeNode root, ArrayList<Integer> list, Queue<TreeNode> queue){
if(root!=null){
list.add(root.val);
queue.offer(root.left);
queue.offer(root.right);
}
if(!queue.isEmpty())
PrintFromTopToBottom(queue.poll(),list,queue);
}
}
2017.6.2 第二遍做
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
Queue<TreeNode> q = new LinkedList<>();
ArrayList<Integer> ret = new ArrayList<>();
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
if(root == null){
return ret;
}
ret.add(root.val);
q.add(root.left);
q.add(root.right);
while(!q.isEmpty()){
PrintFromTopToBottom(q.remove());
}
return ret;
}
}