|
| 1 | +/* |
| 2 | + |
| 3 | + Date: Dec 20, 2014 |
| 4 | + Problem: Validate Binary Search Tree |
| 5 | + Difficulty: Medium |
| 6 | + Source: https://oj.leetcode.com/problems/validate-binary-search-tree/ |
| 7 | + Notes: |
| 8 | + Given a binary tree, determine if it is a valid binary search tree (BST). |
| 9 | + Assume a BST is defined as follows: |
| 10 | + The left subtree of a node contains only nodes with keys less than the node's key. |
| 11 | + The right subtree of a node contains only nodes with keys greater than the node's key. |
| 12 | + Both the left and right subtrees must also be binary search trees. |
| 13 | +
|
| 14 | + Solution: Recursion. 1. Add lower & upper bound. O(n) |
| 15 | + 2. Inorder traversal with one additional parameter (value of predecessor). O(n) |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * Definition for binary tree |
| 20 | + * public class TreeNode { |
| 21 | + * int val; |
| 22 | + * TreeNode left; |
| 23 | + * TreeNode right; |
| 24 | + * TreeNode(int x) { val = x; } |
| 25 | + * } |
| 26 | + */ |
| 27 | +public class Solution { |
| 28 | + boolean isValidBSTRe(TreeNode root, long left, long right) |
| 29 | + { |
| 30 | + if(root == null) return true; |
| 31 | + return left < root.val && root.val < right && |
| 32 | + isValidBSTRe(root.left,left,root.val) |
| 33 | + && isValidBSTRe(root.right, root.val, right); |
| 34 | + } |
| 35 | + public boolean isValidBST_1(TreeNode root) { |
| 36 | + if (root == null) return true; |
| 37 | + return isValidBSTRe(root, (long)Integer.MIN_VALUE - 1, (long)Integer.MAX_VALUE + 1); |
| 38 | + } |
| 39 | + boolean isValidBST(TreeNode root) { |
| 40 | + long[] val = new long[1]; |
| 41 | + val[0] = (long)Integer.MIN_VALUE - 1; |
| 42 | + return inorder(root, val); |
| 43 | + } |
| 44 | + boolean inorder(TreeNode root, long[] val) { |
| 45 | + if (root == null) return true; |
| 46 | + if (inorder(root.left, val) == false) |
| 47 | + return false; |
| 48 | + if (root.val <= val[0]) return false; |
| 49 | + val[0] = root.val; |
| 50 | + return inorder(root.right, val); |
| 51 | + } |
| 52 | +} |
0 commit comments