Skip to content

Commit 527344d

Browse files
committed
Complexity appears to be O(n lgn), but actually O(n)
1 parent 962b1e6 commit 527344d

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

src/BalancedBinaryTree/Solution.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
*/
1515
public class Solution {
1616
/**
17-
* O(n lgn)
17+
* O(n lgn)?
18+
* Actually it is O(n)
19+
* \sum_{i=0}^{h-1} 2^i (h-i)
1820
* @param root
1921
* @return
2022
*/
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

0 commit comments

Comments
 (0)