【LeetCode】104. Maximum Depth of Binary Tree
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// curdep记录当前深度,max记录最大深度
void dep(TreeNode* root, int curdep, int &max) {
if (root->left != NULL) {
// 更新最大深度
if (curdep + 1 > max) max = curdep + 1;
dep(root->left, curdep + 1, max);
}
if (root->right != NULL) {
if (curdep + 1 > max) max = curdep + 1;
dep(root->right, curdep + 1, max);
}
}
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
int max = 1;
dep(root, 1, max);
return max;
}
};