题目描述,从上往下,从左往右打印二叉树
思路:就是层序遍历,创建一个Arraylist res作为结果返回,创建一个qunue用来存放根节点,用一个循环来遍历所有节点
java程序:
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> res = new ArrayList<Integer>();
if(root==null)
return res;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
TreeNode node = null;
while(!queue.isEmpty()){
node = queue.poll();
if(node.left!=null){
queue.offer(node.left);
}
if(node.right!=null){
queue.offer(node.right);
}
res.add(node.val);
}
return res;
}
}