Topic 4.6 Write an algorithm to find the ‘next’ node (i.e.,in-order successor)of a given node in a binary search tree. You may assume that each node has a link to its parent.
方法:
If n has a right subtree,
If n doesn’t have a right subtree, we are done traversing n’s subtree. We need to pick up where we left off with n’ parent, x. If n was to the left x, the next node should be x. (in-order). If n was to the right of x, we have fully traversed x’s subtree, go up, return x’s parent.
If we hit the rightmost, we should return null.
public class C4_6 {
public static TreeNode inorderSucc(TreeNode n) {
if (n == null) return null;//情况3:到达最右,返回null
//情况1:头结点,有右子树
if (n.parent == null || n.right != null) { //注意,要考虑头结点的情况,n.parent==null
return leftMostChild(n.right); //返回的是右子树的leftMostChild
} else {
TreeNode q = n;
TreeNode x = q.parent;//这两个都要存起来,因为向上的话,这两个都要更新
while(x!=null && x.left!=n){//情况2.1 n无右子树,n遍历完;n是一个右子树,n的parent遍历完,向上,返回n的parent的parent.
q = x;
x = x.parent;
}
//情况2。2 n无右子树,n遍历完;n是一个左子树,返回n的parent
return x;
}
}
//该方法的思想就是一直找n.left直到n.left==null.
public static TreeNode leftMostChild(TreeNode n) {
if (n == null) {
return null;
}
while (n.left != null) {
n = n.left;
}
return n;
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
TreeNode root = TreeNode.createMinimalBST(array);
System.out.println(inorderSucc(root).data+"\n"+inorderSucc(inorderSucc(root)).data);
}
}
//结果
6
7