求树的最大深度
附上代码:
1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 int maxDepth(TreeNode *root) {
13 if (root == NULL) return 0;
14 if (root->left == NULL && root->right == NULL) return 1;
15 int ans = 1;
16 if (root->left != NULL) ans = maxDepth(root->left) + 1;
17 if (root->right != NULL) ans = max(ans, maxDepth(root->right)+1);
18
19 return ans;
20 }
21 };