Write catalog title here
1. Title description
2. Problem solving ideas
Depth First Search
Ideas and Algorithms
If we know the maximum depth l and r of the left subtree and the right subtree, then the maximum depth of the binary tree is
max(l,r) + 1
and the maximum of the left subtree and the right subtree The depth can be calculated in the same way. Therefore, we can use the "depth first search" method to calculate the maximum depth of the binary tree. Specifically, when calculating the maximum depth of the current binary tree, the maximum depth of the left subtree and the right subtree can be calculated recursively, and then the maximum depth of the current binary tree can be calculated in O(1) time. Recursion exits when an empty node is visited.
3. Code implementation
class Solution {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
int p = maxDepth(root.left);
int q = maxDepth(root.right);
return Math.max(p, q) + 1;
}
}