题目描述
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
解题思路
以下引用discuss中的一个解释,来体现每次的递归过程:
root: Node[0] has 2 children, Node[1] and Node[2]. and Node[2] has right child Node[3]
our first return will look like this return 1 + max(maxDepth(Node[1]), maxDepth(Node[2]));
we know maxDepth(Node[1]) = 0 because there are no children so when the program calls for maxDepth(Node[1] -> left) and maxDepth(Node[1] -> right) both those will return 0.
As for maxDepth(Node[2]) it will return 1 because Node[2] has 1 right child and to put it all together the recursion looks like this:
1 + max(maxDepth[Node[0 -> left], maxDepth(Node[0] -> right))
=>
1 + max(max(0,0), 1 + max(maxDepth(Node[1] - > left), maxDepth(Node[1] -> right)))
=>
1 + max(max(0,0), 1 + max(max(0,0), max(max(0,0),max(0,0))))
=>
1+max(0,1 + max(0,0))
=>1 + max(0,1)
=> 2
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root==NULL) {
return 0;
}
int left_l=maxDepth(root->left);
int right_l=maxDepth(root->right);
if (left_l>right_l) {
return left_l+1;
}
else
return right_l+1;
}
};