File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed
src/main/java/com/brianway/learning/algorithms/leetcode/medium Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change @@ -58,6 +58,7 @@ Leetcode problems classified by company:
58
58
| 79| Word Search| Medium| Backtracking| 待查题解|
59
59
| 94| Binary Tree Inorder Traversal| Easy| Binary Tree/Stack| 一题多解,待复习|
60
60
| 96| Unique Binary Search Trees| Medium| Dynamic Programming||
61
+ | 98| Validate Binary Search Tree| Medium| Binary Search/Recursion| 一题多解|
61
62
| 101| Symmetric Tree| Easy| Binary Tree/Queue/Stack| 一题多解|
62
63
| 102| Binary Tree Level Order Traversal| Medium| Binary Tree,DFS/BFS| 一题多解|
63
64
| 104| Maximum Depth of Binary Tree| Easy| Binary Tree/Queue||
Original file line number Diff line number Diff line change
1
+ package com .brianway .learning .algorithms .leetcode .medium ;
2
+
3
+ import com .brianway .learning .algorithms .leetcode .common .TreeNode ;
4
+
5
+ /**
6
+ * LeetCode 98. Validate Binary Search Tree
7
+ * Question https://leetcode.com/problems/validate-binary-search-tree/
8
+ * 关键题设:无
9
+ *
10
+ * @auther brian
11
+ * @since 2022/9/7 22:14
12
+ */
13
+ public class ValidateBinarySearchTree {
14
+ public boolean isValidBST (TreeNode root ) {
15
+ return false ;
16
+ }
17
+
18
+ /**
19
+ * 递归
20
+ * <p>
21
+ * 注意:不是只比较每一层的cur > left,cur < right就完了
22
+ * 需要 cur> any of left, cur < any of right
23
+ * <p>
24
+ * 时间复杂度:O(n)
25
+ * 空间复杂度:O(n), 递归用到了栈
26
+ */
27
+ public class ValidateBinarySearchTree0 extends ValidateBinarySearchTree {
28
+ @ Override
29
+ public boolean isValidBST (TreeNode root ) {
30
+ return isValidBST (root , Long .MIN_VALUE , Long .MAX_VALUE );
31
+ }
32
+
33
+ /**
34
+ * 判断root是否在区间 (min, max) 内,左开右开
35
+ * 因为测试数据范围是可能到 Integer.MIN_VALUE 和 Integer.MAX_VALUE,所以这里用long
36
+ *
37
+ * @param root 当前节点
38
+ * @param min 下限
39
+ * @param max 上限
40
+ * @return 是否BST
41
+ */
42
+ public boolean isValidBST (TreeNode root , long min , long max ) {
43
+ if (root == null ) {
44
+ return true ;
45
+ }
46
+
47
+ if (root .val <= min || root .val >= max ) {
48
+ return false ;
49
+ }
50
+
51
+ return isValidBST (root .left , min , root .val )
52
+ && isValidBST (root .right , root .val , max );
53
+ }
54
+ }
55
+
56
+ // TODO 中序遍历,递归/迭代, 然后检查数组是否递增即可
57
+ // 中序遍历可以加一个pre指针,表示上一次访问的节点
58
+
59
+ }
You can’t perform that action at this time.
0 commit comments