104. Maximum Depth of Binary Tree
Easy
115447FavoriteShare
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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its depth = 3.
这道题在做好最小深度(第111题)后做的,只是改点参数就行了。但是温馨提示:
一定要手打代码!
一定要手打代码!
一定要手打代码!
否则会报错:error: stray ‘\302’ in program
全部手打后错误消失。
下面是AC的代码:
/**
* 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 look(TreeNode* root, int dist)
{
if(root!=NULL)
{
dist++;
if(root->left==NULL&&root->right==NULL)
{
return dist;
}
return max(look(root->left,dist),look(root->right,dist));//把min改成max
}
else return 0;//把0x7fffffff改成0
}
int maxDepth(TreeNode* root) {
if(root==NULL)return 0;
int distance=1;
if(root->left==NULL&&root->right==NULL)return 1;
return max(look(root->left,1),look(root->right,1));//把min改成max
}
};