File tree Expand file tree Collapse file tree 2 files changed +48
-1
lines changed Expand file tree Collapse file tree 2 files changed +48
-1
lines changed Original file line number Diff line number Diff line change 14
14
*/
15
15
public class Solution {
16
16
/**
17
- * O(n lgn)
17
+ * O(n lgn)?
18
+ * Actually it is O(n)
19
+ * \sum_{i=0}^{h-1} 2^i (h-i)
18
20
* @param root
19
21
* @return
20
22
*/
Original file line number Diff line number Diff line change
1
+ package ValidateBinarySearchTree ;
2
+
3
+ import commons .datastructures .TreeNode ;
4
+
5
+ /**
6
+ * User: Danyang
7
+ * Date: 1/27/2015
8
+ * Time: 20:52
9
+ *
10
+ * Given a binary tree, determine if it is a valid binary search tree (BST).
11
+
12
+ Assume a BST is defined as follows:
13
+
14
+ The left subtree of a node contains only nodes with keys less than the node's key.
15
+ The right subtree of a node contains only nodes with keys greater than the node's key.
16
+ Both the left and right subtrees must also be binary search trees.
17
+ */
18
+ public class Solution {
19
+ /**
20
+ * Complexity appears to be O(n lgn), but actually O(n)
21
+ * @param root
22
+ * @return
23
+ */
24
+ public boolean isValidBST (TreeNode root ) {
25
+ if (root ==null )
26
+ return true ;
27
+ TreeNode l = getMax (root .left );
28
+ TreeNode r = getMin (root .right );
29
+ if (l !=null && l .val >=root .val || r !=null && r .val <=root .val )
30
+ return false ;
31
+ return isValidBST (root .left ) && isValidBST (root .right );
32
+ }
33
+
34
+ TreeNode getMax (TreeNode cur ) {
35
+ while (cur !=null && cur .right !=null )
36
+ cur = cur .right ;
37
+ return cur ;
38
+ }
39
+
40
+ TreeNode getMin (TreeNode cur ) {
41
+ while (cur !=null && cur .left !=null )
42
+ cur = cur .left ;
43
+ return cur ;
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments