力扣简104 二叉树的最大深度

自己刚看了前两题的递归就去写了!所以一下就过了!但是内存有点垃圾哈哈哈。

没有看迭代题解 

 

 

package leetcode01;

public class Solution104 {
    
    public static int maxDepth(TreeNode root) {
        int depth=0;
        return Depth(root, depth);
    }
    public static int Depth(TreeNode root,int depth) {
        if(root==null) {
            return depth;
        }
        else {
            depth++;
            return Math.max(Depth(root.left, depth), Depth(root.right, depth));
        }
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TreeNode root=new TreeNode(1,new TreeNode(2,new TreeNode(1),null),null);
        System.out.print(maxDepth(root));
    }

}

 

 

1递归题解

    public static int maxDepth(TreeNode root) {
        if(root==null) {
            return 0;
        }
        else {
            return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
        }
    }

 

posted @ 2022-05-19 11:43  Ssshiny  阅读(22)  评论(0)    收藏  举报