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.
分析:简单题,两种经典的方法。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int ret = 0;
public:
int maxDepth(TreeNode *root) {
if(!root) return 0;
ret = DFS(root);
return ret;
}
int DFS(TreeNode *root) {
if(!root->left && !root->right) {
return 1;
}
int r = 0;
int l = 0;
if(root->left) {
r = DFS(root->left);
}
if(root->right) {
l = DFS(root->right);
}
return max(r, l) + 1;
}
};
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int ret = 0;
public:
int maxDepth(TreeNode *root) {
if(!root) return 0;
DFS(root, 0);
return ret;
}
void DFS(TreeNode *root, int item) {
item++;
if(!root->left && !root->right) {
ret = max(ret, item);
return ;
}
if(root->left) DFS(root->left, item);
if(root->right) DFS(root->right, item);
}
};