Problem description:

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.

1
2
3
4
5
6
7
Example 1:

Input:
2
/ \
1 3
Output: true
1
2
3
4
5
6
7
8
Example 2:

5
/ \
1 4
/ \
3 6
Output: false

Explanation: The input is: [5,1,4,null,null,3,6]. The root node’s value
is 5 but its right child’s value is 4.

Solution1:

Binary search tree:
left subtree < node < right subtree
this looks like a sorted array, so we can use a stack to keep nodes when we do inorder traversal.

We can use a variable to store left node and compare with current one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 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) {
TreeNode* prev = NULL;
return validate(root, prev);
}
bool validate(TreeNode* root, TreeNode* &prev) {//do Inorder traversal
//1. find toward left until the end
//2. set this leftest node as prev
//3. check if prev(left) node is smaller than root
//4. check right subtree
if (root == NULL) return true;
if (!validate(root->left, prev)) return false;
if (prev != NULL && root->val <= prev->val ) return false; //previous node is from left side, so it should be smaller than right side node
prev = root;
return validate(root->right, prev);
}
};

time complexity: $O(n)$
space complexity: $O(logn)$

Solution2:

Another solution is to use BFS, with a stack.
Find the left most node, and then start to validate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<TreeNode*> s;
TreeNode *p = root, *pre = NULL;
while (p || !s.empty()) {
while (p) {
s.push(p);
p = p->left;
}
TreeNode *t = s.top(); s.pop();
if (pre && t->val <= pre->val) return false;
pre = t;
p = t->right;
}
return true;
}
};

time complexity: $O(n)$
space complexity: $O(n)$