文章作者:Tyan
博客:noahsnail.com | CSDN |
1. Description
2. Solution
- Version 1
/**
* 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:
int maxDepth(TreeNode* root) {
int maxDepth = 0;
preorderTraverse(root, 0, maxDepth);
return maxDepth;
}
private:
void preorderTraverse(TreeNode* root, int depth, int& maxDepth) {
if(!root) {
return;
}
depth++;
if(depth > maxDepth) {
maxDepth = depth;
}
preorderTraverse(root->left, depth, maxDepth);
preorderTraverse(root->right, depth, maxDepth);
}
};
- Version 2
/**
* 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:
int maxDepth(TreeNode* root) {
if(!root) {
return 0;
}
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
Reference
- https://leetcode.com/problems/maximum-depth-of-binary-tree/description/