[Lintcode] Inorder Successor in BST
Inorder Successor in BST
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Given tree = [2,1] and node = 1:
2
/
1
return node 2.
Given tree = [2,1,3] and node = 2:
2
/ \
1 3
return node 3.
If the given node has no in-order successor in the tree, return null.
O(h), where h is the height of the BST.
SOLUTION :
如果在面试的时候,首先应该考虑的是这个点,面试官给不给他的父亲节点,也就是有没有node.parent。如果有父亲节点,那么这个题就很好做了。
这个题是要找输入node的中序时候的下一个点。这种时候首先,我们要先找到这个点,再分情况去讨论,由于中序下一位是比这个点大的最近的一个点,所以我们要看的是这个点有没有右子树,从这个出发点来考虑。
解题步骤:
1,找到这个点。
2,分情况讨论:
1)找到的点没有右子树,那么我们就从这个点开始向上找他的父亲节点,在父亲节点中第一个比他大的就是successor(其实就是中序遍历)。
在没有parent指针的情况下,我们就要提前纪录这个第一个比node点大的父亲节点,方法就是,每次root向左边移动*之前*的时候记录这个root,向右边移动则不需要记录,这样就可以记录下这个比它大的最近父节点了。(再仔细说一下这个作用:纪录向左移动前的点就是纪录比root点大的下一个点,向右不需要纪录是因为这个点本身比上一个点大,不需要纪录,这个点不可能成为右儿子的successor)
2)找到的点有右子树,那么就要找他右子树里面的最小点,这个点就是他的successor。
3)特殊情况,没有找到这个点,返回null。
具体看代码:
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
TreeNode successor = null;
//find the position of node and lowest root
while (root != null && root.val != p.val){
if (p.val < root.val){
successor = root;
root = root.left;
} else {
root = root.right;
}
}
if (root == null){
return null;
}
if (root.right == null){
return successor;
}
//when root.right != null
root = root.right;
//找右儿子的最小值也就是一直在它右子树第一个根节点一直向左遍历到叶节点
while (root.left != null){
root = root.left;
}
return root;
}
}
作者:http://www.cnblogs.com/tritritri/
浙公网安备 33010602011771号