Thursday, May 22, 2014

LeetCode: Validate Binary Search Tree

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.


We can check the tree by the definition of binary search tree. Or we can use inorder traversal to traverse all nodes in the tree and then check if the elements are in an increasing order.

C++ Code:

/*
 * func: valid_BST_helper
 * goal: helper function for valid BST
 * @param root: root node
 * @param max: max value for this tree
 * @param min: min value for this tree
 * return: true or false
 */
bool valid_BST_helper(TreeNode *root, int max, int min){
    if(root == nullptr){
        return true;
    }
    
    if(root->val < min || root->val > max){
        return false;
    }
    return valid_BST_helper(root->left, root->val, min) && valid_BST_helper(root->right, max, root->val);
}

/*
 * func: valid_BST
 * goal: to check if input tree is BST
 * @param root: root node of the binary tree
 * return: true or false
 */
bool valid_BST(TreeNode *root){
    return valid_BST_helper(root, numeric_limits<int>::max(), numeric_limits<int>::min());
}

Python Code:

def inorder_traversal(root, li):
    if not root:
        return
    else:
        inorder_traversal(root.left)
        li.append(root.val)
        inorder_traversal(root.right)

# func: to check if a tree is a BST
# @param root: root node of the tree
# @return: True or False
def valid_BST(root):
    li = []
    inorder_traversal(root, li)
    for i in xrange(1, len(li)):
        if li[i] <= li[i-1]:
            return False
    return True

Reference Link:

1. A program to check if a binary tree is BST or not | GeeksforGeeks http://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/

No comments:

Post a Comment