Given the root of a binary tree, determine if it is a valid binary search tree (BST).
LeetCode-98: Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
left
subtree of a node contains only nodes with keys less than the node’s key.right
subtree of a node contains only nodes with keys greater than the node’s key.left
and right
subtrees must also be binary search trees.A straightforward approach that comes to mind is to compare the root node with the left and right child nodes. If the root node is greater than the left child node and less than the right child node, then the tree is a valid BST. We can recursively check the left and right subtrees to determine if they are valid BSTs.
But this approach is not correct. Consider the following tree:
5
/ \
1 8
/ \
4 9
The tree above is not a valid BST even though in respective subtrees, the root node is greater than the left child node and less than the right child node.
The correct approach is to keep track of the range of values that the current node should fall into.
(-inf, inf)
.(-inf, root.val)
,(root.val, inf)
.This is because the left child node should have a value less than the root node, and the right child node should have a value greater than the root node. We can recursively check the left and right subtrees with the updated range.
Here is a Java implementation of the approach:
public boolean isValidBST(TreeNode root) {
return check(root, Long.MAX_VALUE, Long.MIN_VALUE);
}
private boolean check(TreeNode root, long max, long min){
if(null == root){
return true;
}
// If the current node value is not within the range, return false
if(root.val >= max || root.val <= min){
return false;
}
// Check the left and right subtrees with the updated range
// For the left subtree, the range is (min, root.val)
// i.e. the maximum value that any node in the left subtree can have should
// be less than the root value
// For the right subtree, the range is (root.val, max)
// i.e. the minimum value that any node in the right subtree can have should
// be greater than the root value
return check(root.left, root.val, min) && check(root.right, max, root.val);
}
The overall time complexity of the approach is $O(N)$, where $N$ is the number of nodes in the binary tree. We are visiting each node once.
Be notified of new posts. Subscribe to the RSS feed.