Tuesday 4 October 2016

Validate Binary Search Tree (LeetCode)

Problem: Given a binary tree, determine if it is a valid binary search tree (BST).

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        return(checkBST(root, NULL, NULL));
    }
    
    bool checkBST(TreeNode* root, TreeNode* min, TreeNode* max)
    {
        if(root==NULL) return true;
        
        
        if(min && root->val <= min->val) return false;
        if(max && root->val >= max->val) return false;
        
        if(!checkBST(root->left, min, root)) return false;
        if(!checkBST(root->right, root, max)) return false;
    return true;
    }
    
};

No comments:

Post a Comment