-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidateBinarySearchTree.java
More file actions
106 lines (89 loc) · 2.66 KB
/
Copy pathValidateBinarySearchTree.java
File metadata and controls
106 lines (89 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
public class ValidateBinarySearchTree {
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution_v1 {
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
if (root.left != null && root.left.val >= root.val) {
return false;
}
if (root.right != null && root.right.val <= root.val) {
return false;
}
return isValidBST(root.left) && isValidBST(root.right);
}
}
class MySolution {
public boolean isValidBST(TreeNode root) {
return validateChildren(root, root.val);
}
public boolean validateChildren(TreeNode node, int rootVal) {
if (node == null) {
return true;
}
if (!validateLeft(node.left, rootVal) || !validateRight(node.right, rootVal)) {
return false;
}
return validateChildren(node.left, node.val) && validateChildren(node.right, node.val);
}
public boolean validateRight(TreeNode node, int rootVal) {
if (node == null) {
return true;
}
if (node.val <= rootVal) {
return false;
}
if (node.left != null && node.left.val <= rootVal) {
return false;
}
if (node.right != null && node.right.val <= rootVal) {
return false;
}
return validateRight(node.left, rootVal) && validateRight(node.right, rootVal);
}
public boolean validateLeft(TreeNode node, int rootVal) {
if (node == null) {
return true;
}
if (node.val >= rootVal) {
return false;
}
if (node.left != null && node.left.val >= rootVal) {
return false;
}
if (node.right != null && node.right.val >= rootVal) {
return false;
}
return validateLeft(node.left, rootVal) && validateLeft(node.right, rootVal);
}
}
class Solution {
public boolean isValidBST(TreeNode root) {
return validate(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean validate(TreeNode node, long min, long max) {
if (node == null) {
return true;
}
if (node.val <= min || node.val >= max) {
return false;
}
return validate(node.left, min, node.val) && validate(node.right, node.val, max);
}
}