Skip to content

Instantly share code, notes, and snippets.

@codetalks-new
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save codetalks-new/236235e7f30825de68dc to your computer and use it in GitHub Desktop.

Select an option

Save codetalks-new/236235e7f30825de68dc to your computer and use it in GitHub Desktop.
Validate Binary Search Tree leetcode https://leetcode.com/problems/validate-binary-search-tree/ Java Solution
/**
* Definition for a binary tree node.
* 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;
}
boolean isLeftBranchValid = true;
boolean isRightBranchValid = true;
if(root.left != null){
isLeftBranchValid = isValidBranch(root.left,Long.MIN_VALUE,root.val);
}
if(root.right != null){
isRightBranchValid = isValidBranch(root.right,root.val,Long.MAX_VALUE);
}
return (isLeftBranchValid && isRightBranchValid);
}
public static boolean isValidBranch(TreeNode branch,long minLimit,long maxLimit){
if(branch.val <= minLimit || branch.val >= maxLimit){
return false;
}
boolean isLeftBranchValid = true;
boolean isRightBranchValid = true;
if(branch.left != null){
isLeftBranchValid = isValidBranch(branch.left,minLimit,branch.val);
}
if(branch.right != null){
isRightBranchValid = isValidBranch(branch.right,branch.val,maxLimit);
}
return (isLeftBranchValid && isRightBranchValid);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment