File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
validate-binary-search-tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a binary tree node.
3+ * public class TreeNode {
4+ * int val;
5+ * TreeNode left;
6+ * TreeNode right;
7+ * TreeNode() {}
8+ * TreeNode(int val) { this.val = val; }
9+ * TreeNode(int val, TreeNode left, TreeNode right) {
10+ * this.val = val;
11+ * this.left = left;
12+ * this.right = right;
13+ * }
14+ * }
15+ */
16+ /**
17+ * time complexity: O(n)
18+ * space complexity: O(h)
19+ */
20+ class Solution {
21+ public boolean isValidBST (TreeNode root ) {
22+ return isValidRange (root , Long .MIN_VALUE , Long .MAX_VALUE );
23+ }
24+
25+ private boolean isValidRange (TreeNode root , long min , long max ) {
26+ if (root == null ) return true ;
27+
28+ if (root .val <= min || root .val >= max ) return false ;
29+
30+ return isValidRange (root .left , min , root .val )
31+ && isValidRange (root .right , root .val , max );
32+ }
33+
34+ }
You can’t perform that action at this time.
0 commit comments