Thursday, July 23, 2015

Leetcode 98: validate BST

Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.
每次往下传值,同时传入lower bound 和upper bound, 但是leetcode上有一个corner case 不能处理,就是如果root的值是INT_MIN / INT_MAX的时候, 会出现问题,解决办法很简单,直接传LONG_MIN/ LONG_MAX就可以了。




class Solution {
private:
    bool helper(TreeNode* &root, long lower, long upper) {
        //base caes
        if (root == NULL) return true;
        if (root->val > lower && root->val < upper) {
            return helper(root->left, lower, root->val) && helper(root->right, root->val, upper);
        } else return false;
    }
public:
    bool isValidBST(TreeNode* root) {
        //sanity check
        if (root == NULL) return true;
        if (!root->left && ! root->right) return true;
        return helper(root, LONG_MIN, LONG_MAX);
    }
};

No comments:

Post a Comment