in-order successor with parent pointer
2. Validate Binary Search Tree
- ResultType: min, max, isValid
- in-order traversal, check values: need a ptr for the previous value
- min & max: null
- 第二种方法一般可行,但是如果有duplicates的话就无法判断了,比如left <= root < right
6 6
/ \
6 6
第二个例子明显不符合条件,但是Inorder traversal是无法甄别的。
如果是strict bst,那就可以。
- 第三种方法实现起来超级简单的。问题是,我用的是Integer,如果root.val很大的话,就不能储存了。
- O(n) time: touch all N nodes
- O(log n) space: for a balanced tree. At most O(log n) recursive calls on the stack.
3. Inorder Successort in BST
4. in-order successor with parent pointer
leftmost child of right subtree / if doesn't have right subtree, then go up until right turn
public TreeNode inorderSucc(TreeNode n) {
if (n == null) return root;
if (n.right != null) {
return getLeftMostChild(n);
} else {
TreeNoe parent = n.parent;
//parent.right == n means n is larger than parent
while (parent != null && parent.right == n) {
n = parent;
parent = parent.parent;
}
return parent;
}
}
private TreeNode getLeftMostChild(TreeNode n) {
while (n.left != null){
n = n.left;
}
return n;
}