Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

A typical recursion one.

class Solution 
{
    bool _verify(vector<int> &in, int i, int j, 
                int low, int high)
    {
        if (i > j) return true; // empty
        
        int root = in[i];
        if (!(root >= low && root <= high)) return false;
        if (i == j) return true;

        //    find split
        int inx = i + 1;
        while (inx <= j && in[inx] < root)
            inx++;

        return _verify(in, i + 1, inx - 1, low, root - 1) &&
            _verify(in, inx, j, root + 1, high);
    }
public:
    bool verifyPreorder(vector<int>& preorder) 
    {
        return _verify(preorder, 0, preorder.size() - 1,
                        INT_MIN, INT_MAX);
    }
};
posted on 2015-08-20 14:59  Tonix  阅读(245)  评论(0编辑  收藏  举报