LintCode/Validate Binary Search Tree

Problem Summary

Given a binary tree, determine if it is a binary search tree.

Assume a BST is defined as follows:

  1. The left subtree of a node contains only nodes with keys less than the node’s key.
  2. The right subtree of a node contains only nodes with keys greater than the node’s key.
  3. Both the left and right subtrees must also be binary search trees.
  4. A single node tree is a BST.

Solution 1

We can use DFS to check whether the tree is a BST.

For each node, we use its value to determine the maximum value of its left subtree and the minimum value of its right subtree.

Solution 2

Since the BST required in this problem should not contain duplicate values, we can do an inorder traversal, and if the sequence is stictly increasing, the tree is a BST.

Code for Solution 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
/*
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
bool isValidBST(TreeNode * root) {
return is_valid_bst(root,INT_MIN,INT_MAX);
}
bool is_valid_bst(TreeNode *root,int min,int max)
{
if (root == NULL)
return true;
if (root->val < min || root->val > max)
return false;
return is_valid_bst(root->left,min,root->val-1) && is_valid_bst(root->right,root->val+1,max);
}
};