Last active
August 29, 2015 14:23
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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