@@ -38,20 +38,45 @@ public boolean isValidBST(TreeNode root) {
3838
3939 private boolean helper (TreeNode root , long min , long max ) {
4040 if (root == null ) return true ;
41+ if (root .val <= min || root .val >= max ) return false ;
42+ return helper (root .left , min , root .val ) && helper (root .right , root .val , max );
43+ }
4144
42- if (root .val <= min || root .val >= max ) {
43- return false ;
44- }
4545
46- return helper (root .left , min , root .val ) && helper (root .right , root .val , max );
46+ public boolean isValidBST2 (TreeNode root ) {
47+ if (root == null ) return true ;
48+ return isValidBST (root , new int []{0 , 0 });
4749 }
4850
51+ private boolean isValidBST (TreeNode root , int [] bounds ) {
52+ bounds [0 ] = root .val ;
53+ bounds [1 ] = root .val ;
54+ if (root .left == null && root .right == null ) {
55+ return true ;
56+ }
57+
58+ if (root .left != null ) {
59+ int [] leftBounds = new int []{0 , 0 };
60+ boolean left = isValidBST (root .left , leftBounds );
61+ if (!left || leftBounds [1 ] >= root .val ) return false ;
62+ bounds [0 ] = leftBounds [0 ];
63+ }
64+
65+ if (root .right != null ) {
66+ int [] rightBounds = new int []{0 , 0 };
67+ boolean right = isValidBST (root .right , rightBounds );
68+ if (!right || rightBounds [0 ] <= root .val ) return false ;
69+ bounds [1 ] = rightBounds [1 ];
70+ }
71+
72+ return true ;
73+ }
4974
5075
5176 /**
5277 * https://discuss.leetcode.com/topic/46016/learn-one-iterative-inorder-traversal-apply-it-to-multiple-tree-questions-java-solution
5378 */
54- public boolean isValidBST2 (TreeNode root ) {
79+ public boolean isValidBST3 (TreeNode root ) {
5580 if (root == null ) return true ;
5681 Stack <TreeNode > stack = new Stack <>();
5782 TreeNode pre = null ;
0 commit comments