剑指offer22题

import java.util.ArrayList;

class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}

/**
 * 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
 * 思路
 * 打印一层,遍历一层
 */
public class Solution22 {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {

        ArrayList<Integer> arrayList = new ArrayList();
        if (root == null) {
            return arrayList;
        }
        arrayList.add(root.val);
        printFromTopToBottom(root.left, root.right, arrayList);
        return arrayList;
    }

    private void printFromTopToBottom(TreeNode left, TreeNode right, ArrayList<Integer> arrayList) {
        if (left == null && right == null) {
            return;
        }
        if (left != null) {
            arrayList.add(left.val);
        }
        if (right != null) {
            arrayList.add(right.val);
        }
        if (left!=null){
            printFromTopToBottom(left.left, left.right, arrayList);
        }
        if (right != null){
            printFromTopToBottom(right.left, right.right, arrayList);
        }
    }


}
原文地址:https://www.cnblogs.com/Adam-Ye/p/13541528.html