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.
Subscribe to see which companies asked this question
递归解法。
两种,第一种写法清晰,明了,更容易理解,但效率低,因为辅存不必要的信息了。
代码;
/**
* 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==NULL) return 0;
return findMaxDepth(root,0);
}
int findMaxDepth(TreeNode* root,int len)
{
if(root==NULL) return len;
int t1=len;
int t2=len;
if(root->left) t1=findMaxDepth(root->left,t1+1);
if(root->right) t2=findMaxDepth(root->right,t2+1);
return max(t1,t2);
// return max(findMaxDepth(root->left,len+1),findMaxDepth(root->right,len+1));
}
};
代码2 实际上就是取消了t1,t2.
代码:
/**
* 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==NULL) return 0;
return findMaxDepth(root,0);
}
int findMaxDepth(TreeNode* root,int len)
{
if(root==NULL) return len;
// int t1=len;
// int t2=len;
// if(root->left) t1=findMaxDepth(root->left,t1+1);
// if(root->right) t2=findMaxDepth(root->right,t2+1);
// return max(t1,t2);
return max(findMaxDepth(root->left,len+1),findMaxDepth(root->right,len+1));
}
};