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

(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[n],rightHightest[n],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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值