题目:
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路:
- 将树分为若干个子树,每个子树都是由头节点和左右子节点构成;
- 遍历一个小的子树,判断是否有头节点,再进行递归就可以了。
import java.util.ArrayList;
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution {
ArrayList<Integer> array = new ArrayList<Integer>();
int count = 1;
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
if(root == null){
return array;
}
if(root != null){
if(count == 1){ //只打印头结点
array.add(root.val);
count++;
}
if(root.left != null){
array.add(root.left.val);
}
if(root.right != null){
array.add(root.right.val);
}
PrintFromTopToBottom(root.left);
PrintFromTopToBottom(root.right);
}
return array;
}
}