Skip to content

Commit 6ad6993

Browse files
committed
solve validate-bst
1 parent fccf9b6 commit 6ad6993

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// link: https://leetcode.com/problems/validate-binary-search-tree/description/
2+
// difficulty: Medium
3+
/**
4+
* Definition for a binary tree node.
5+
* public class TreeNode {
6+
* int val;
7+
* TreeNode left;
8+
* TreeNode right;
9+
* TreeNode() {}
10+
* TreeNode(int val) { this.val = val; }
11+
* TreeNode(int val, TreeNode left, TreeNode right) {
12+
* this.val = val;
13+
* this.left = left;
14+
* this.right = right;
15+
* }
16+
* }
17+
*/
18+
class Solution1 {
19+
// Problem:
20+
// * return: check if tree is a valid BST
21+
// * left subtree contains keys strictly less than node's key
22+
// * right subtree contains keys strictly greater than node's key
23+
// * recursive structure
24+
// Solution:
25+
// * Time Complexity: O(N)
26+
// * Space Complexity(in terms of call stack):
27+
// * O(N) if skewed
28+
// * O(log N) if not skewed
29+
public boolean isValidBST(TreeNode root) {
30+
// checklist:
31+
// * is subtree a valid bst
32+
// * left subtree : is max value of subtree less than node
33+
// * right subtree : is min value of subtree greater than node
34+
return isValid(root, null, null);
35+
}
36+
37+
private boolean isValid(TreeNode node, Integer min, Integer max) {
38+
if(node == null) return true;
39+
40+
int val = node.val;
41+
42+
if(min != null && val <= min) return false;
43+
if(max != null && val >= max) return false;
44+
45+
if(!isValid(node.left, min, val)) return false;
46+
if(!isValid(node.right, val, max)) return false;
47+
48+
return true;
49+
}
50+
}
51+
52+
// in-order traversal approach
53+
// * reads from left-most to right (strictly increasing val order expected)
54+
class Solution2 {
55+
private Integer prev;
56+
57+
// Solution:
58+
// * Time Complexity: O(N)
59+
// * Space Complexity(in terms of call stack):
60+
// * O(N) if skewed
61+
// * O(log N) if not skewed
62+
public boolean isValidBST(TreeNode root) {
63+
prev = null;
64+
return inorder(root);
65+
}
66+
67+
private boolean inorder(TreeNode node) {
68+
// reached end without failure
69+
if(node == null) return true;
70+
71+
// inorder so travel left first
72+
if(!inorder(node.left)) return false;
73+
74+
// if node value is not greater than prev, it isn't a BST in in-order
75+
if(prev != null && node.val <= prev) return false;
76+
prev = node.val;
77+
78+
return inorder(node.right);
79+
}
80+
}

0 commit comments

Comments
 (0)