104. 二叉树的最大深度Leetcode

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
//使用递归
//左子树和右子树深度的最大值
class Solution {
    public int maxDepth(TreeNode root) {
        
        if(root == null){//递归的出口,可以看做解决这个问题的最小的规模为树是空着的时候
            return 0;
        }else if(root.left == null && root.right == null){//如果只有根节点,返回1
            return 1;
        }else{
            int left = maxDepth(root.left);
            int right = maxDepth(root.right);
            return 1 + (left > right ? left : right);
        }
        
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32682177/article/details/81777858