Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created December 20, 2012 23:19
Show Gist options
  • Save zac-xin/4349492 to your computer and use it in GitHub Desktop.
Save zac-xin/4349492 to your computer and use it in GitHub Desktop.
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.
/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
return helper(root, Integer.MAX_VALUE, Integer.MIN_VALUE);
}
public boolean helper(TreeNode root, int max, int min){
if(root == null)
return true;
if(root.val < max && root.val > min && helper(root.left, root.val, min) &&
helper(root.right, max, root.val))
return true;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment