您的位置:首页 > 移动开发

Minimum Depth of Binary Tree & Length of Last Word & Trapping Rain Water

2014-05-10 16:52 405 查看
(1) Minimum Depth of Binary Tree

class Solution {
private:
void solve(TreeNode *root, int curDep, int &minDep){
if(!root)
return;
if(!root->left && !root->right)
{
minDep=min(curDep,minDep);
return;
}
curDep++;
solve(root->left,curDep,minDep);
solve(root->right,curDep,minDep);
}

public:
int minDepth(TreeNode *root) {
if(!root)
return 0;
int minDep=1000000;
solve(root,1,minDep);
return minDep;
}
};另一种不需要预设最小值得方法[1]。

(2) Length of Last Word

class Solution {
public:
int lengthOfLastWord(const char *s) {
char cur=*s;
int i=0,len=0,prelen=0;

while(cur!='\0')
if(cur==' ')
{
prelen=len>0?len:prelen;
len=0;
i++;
cur=*(s+i);
if(cur=='\0')
return prelen;
}
else
{
len++;
i++;
cur=*(s+i);
}
return len;
}
};

(3) Trapping Rain Water
根据[2]: 对某个值A[i]来说,能trapped的最多的water取决于在i之前最高的值leftMostHeight[i]和在i右边的最高的值rightMostHeight[i](均不包含自身)。

如果min(left,right) > A[i],那么在i这个位置上能trapped的water就是min(left,right) – A[i]。

有了这个想法就好办了,第一遍从左到右计算数组leftMostHeight,第二遍从右到左计算rightMostHeight。

时间复杂度是O(n)。
class Solution {
public:
int trap(int A[], int n) {
int curHeight=A[0],sum=0;
int leftHighest
,rightHightest
,maxHeight,water,high;

maxHeight=0;
for(int i=0;i<n;i++)
{
leftHighest[i]=maxHeight;
maxHeight=max(maxHeight,A[i]);
}

maxHeight=0;
for(int i=n-1;i>=0;i--)
{
rightHightest[i]=maxHeight;
maxHeight=max(maxHeight,A[i]);
}

water=0;
for(int i=0;i<n;i++)
{
high=min(leftHighest[i],rightHightest[i])-A[i];
if(high>0)
water+=high;
}
return water;
}
};

参考:
[1]http://www.cnblogs.com/remlostime/archive/2012/11/12/2766608.html

[2]http://blog.csdn.net/doc_sgl/article/details/12307171
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: