File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
validate-binary-search-tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public boolean isValidBST (TreeNode root ) {
3+ return (root .left == null || isValidBSTMax (root .left , root .val ))
4+ && (root .right == null || isValidBSTMin (root .right , root .val ));
5+ }
6+
7+ private boolean isValidBSTMax (TreeNode root , int max ) {
8+ if (root .val >= max ) {
9+ return false ;
10+ }
11+
12+ return (root .left == null || isValidBSTMax (root .left , root .val ))
13+ && (root .right == null || isValidBSTMinMax (root .right , root .val , max ));
14+ }
15+
16+ private boolean isValidBSTMin (TreeNode root , int min ) {
17+ if (root .val <= min ) {
18+ return false ;
19+ }
20+
21+ return (root .left == null || isValidBSTMinMax (root .left , min , root .val ))
22+ && (root .right == null || isValidBSTMin (root .right , root .val ));
23+ }
24+
25+ private boolean isValidBSTMinMax (TreeNode root , int min , int max ) {
26+ if (root .val >= max || root .val <= min ) {
27+ return false ;
28+ }
29+
30+ return (root .left == null || isValidBSTMinMax (root .left , min , root .val ))
31+ && (root .right == null || isValidBSTMinMax (root .right , root .val , max ));
32+ }
33+
34+ public class TreeNode {
35+ int val ;
36+ TreeNode left ;
37+ TreeNode right ;
38+
39+ TreeNode () {
40+ }
41+
42+ TreeNode (int val ) {
43+ this .val = val ;
44+ }
45+
46+ TreeNode (int val , TreeNode left , TreeNode right ) {
47+ this .val = val ;
48+ this .left = left ;
49+ this .right = right ;
50+ }
51+ }
52+ }
You can’t perform that action at this time.
0 commit comments