LeetCode104 二叉树的最大深度 详细解读

题目: 简单题
给定一个二叉树,找出其最大深度。

示例:略

思路:
本题较为简单,使用递归即可解决。如果节点为空,则高度为0,否则开始递归,返回值时需要进行+1,否则,返回值不会变化。
代码:

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

猜你喜欢

转载自blog.csdn.net/weixin_43744992/article/details/121605811