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);
        }
    }


}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-03
  • 2021-12-29
猜你喜欢
  • 2021-09-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案