leetcode104. maximum depth of binary tree

计算二叉树的最大深度,递归解法,分别计算左右子树的最大深度,递归出口为到达叶子结点。

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class {
public:
int maxDepth(TreeNode* root) {
if(root==NULL) //递归出口,到达叶子结点
return 0;
int maxLeft=maxDepth(root->left); //左右子树
int maxRight=maxDepth(root->right);
return (maxLeft>maxRight)?maxLeft+1:maxRight+1;
}
};

传送门:leetcode104