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.
===============
Analysis:
Basic idea is to validate all rules of BST for each node in the given binary tree. Accordingly, for each node (current node), we compare it to all the nodes in its left sub-tree, and all the node in its right sub-tree. If there is any node in in its left or right sub-trees vibrates the BST rule, return false. Otherwise, further check current node's left child and right child.
Obviously, we need a recursive function to check all the nodes in given binary tree. Besides, for compare current node with all the nodes in its left and right sub-trees, we need another recursive function.
One more thing need to be careful is to define the false condition while comparing current node to nodes in its left and right sub-trees.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
if(root == null) return true; // exit
// compare current node with all nodes in its left sub-tree and right sub-tree (be careful!)
if(!helper(root.val, root.left, true)||!helper(root.val, root.right, false)) return false;
// current node validated
return isValidBST(root.left) && isValidBST(root.right);
}
public boolean helper(int value, TreeNode node, boolean left){
if(node == null) return true;
if(left == true && node.val >= value) return false;
if(left == false && node.val <= value) return false;
return helper(value, node.left, left) && helper(value, node.right, left);
}
}