Maximum Depth of Binary Tree
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;
}
};
每天早上叫醒你的不是闹钟,而是心中的梦~

浙公网安备 33010602011771号