1. 程式人生 > >劍指offer——(13)從上往下列印二叉樹

劍指offer——(13)從上往下列印二叉樹

遵從先上後下,先左後右的原則,用if——else遞迴即可。 

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 {
    ArrayList<Integer> AL = new ArrayList<Integer>();
	boolean boo = false;
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {    		
        if(root==null) return AL;		
        if(boo==false){
            AL.add(root.val);
            boo=true;
        }
        if(root.left!=null&&root.right!=null){
            AL.add(root.left.val);
            AL.add(root.right.val);
            PrintFromTopToBottom(root.left);           
            PrintFromTopToBottom(root.right);
        }
        else if(root.left!=null&&root.right==null) {
        	AL.add(root.left.val);
        	PrintFromTopToBottom(root.left); 
        }
        else if(root.right!=null&&root.left==null) {
        	AL.add(root.right.val);
        	PrintFromTopToBottom(root.right); 
        }
        else {
        	return AL;
        }
        return AL;
    }
}
import java.util.ArrayList;
public class Solution {
    ArrayList<Integer> AL = new ArrayList<Integer>();
	boolean boo = false;
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {    		
        if(root==null) return AL;
        if(boo==false){
            AL.add(root.val);
            boo=true;
        }
        if(root.left!=null) AL.add(root.left.val);
        if(root.right!=null) AL.add(root.right.val);    
        PrintFromTopToBottom(root.left);
        PrintFromTopToBottom(root.right);
        return AL;
    }
}