leetcode 2, 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
20
21
22
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int (TreeNode *root) {
if (root != NULL) {
int imaxDepth = 1;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
imaxDepth = imaxDepth + (leftDepth > rightDepth ? leftDepth : rightDepth);
return imaxDepth;
}
return 0;
}
};