您的位置:首页 > 其它

Maximum Depth of Binary Tree

2013-12-14 04:17 225 查看
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 {
public:
int maxDepth(TreeNode *root) {
int depth = 0;
TreeNode *p = root;
if(!p) return depth;
if(maxDepth(p->left)>maxDepth(p->right))
return depth + maxDepth(p->left);
else
return depth + maxDepth(p->right);

}
};


超时原因:

~很显然, maxDepth(p->left)每次求的时候都计算了两次, 这个真是太不明智了

提醒以后,尽量用变量代替繁琐的实现

~超时后不是考虑用非递归方法, 这个当然也可以, 而是考虑递归方法是否是最优的

正确代码:

/**
* Definition for binary tree
* 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;
int leftdepth = maxDepth(root->left);
int rightdepth= maxDepth(root->right);
if(leftdepth>rightdepth)
return 1 + leftdepth;
return 1 + rightdepth;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: