Given a binary tree, find its maximum depth. The depth of a binary tree is the number of nodes on the longest path from the root node to the farthest leaf node. Explanation: A leaf node is a node that has no child nodes. 【LeetCode Hot 100】

Question 104 of the Hottest Questions 100:

class Solution {
    public int maxDepth(TreeNode root) {
        //当root为null时,二叉树长度为0
        if(root == null){
            return 0;
        }
        //当root左右子树都不为null,整棵树最大长度为左右子树长度的最大值+1;
        return 1 + Math.max(maxDepth(root.left),maxDepth(root.right));
    }
}

Analysis of ideas: When doing this kind of problem, you must learn to convert big problems into small problems. For example, in this problem, if you ask for the maximum depth of a binary tree, you can turn it into finding the maximum depth of its subtree + 1. When its subtree When it is a leaf node, the depth is 1, and when the subtree is empty, the depth is 0.

But the depth of the left tree cannot be superimposed with the depth of the right tree, so we have to take their maximum value, and then we can use recursion to solve it.

Guess you like

Origin blog.csdn.net/weixin_56960711/article/details/123338548