valid binary search tree

class Solution {
public:
    bool valid(TreeNode *node, stack<int>& s)
    {
        if( node == NULL ) return true;
        
        stack<int> left,right;
        
        if( !valid(node->left,left) )
            return false;
        if( !left.empty() )
        {
            if( left.top() >= node->val )
            {
                return false;
            }
            left.pop();
        }
        if( !valid(node->right,right) )
            return false;
        if( !right.empty() )
        {
            int t = right.top();
            right.pop();
            if( right.top() <= node->val )
            {
                right.pop();
                return false;
            }
            right.push(t);
        }
        
        if( !left.empty() )
            s.push(left.top());
        else  s.push(node->val);
        if( !right.empty() )
            s.push(right.top());
        else  s.push(node->val);
        
        return true;
        
    }
    bool isValidBST(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<int> s;
        return valid( root, s );
        
    }
};

 

posted on 2013-07-05 21:55  jumping_grass  阅读(159)  评论(0)    收藏  举报

导航