Successor: 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
已知BST中的一个node, 写算法找到下一个节点(比如:中序遍历)。假定每个节点都有父节点;
successor: 继承者;
思路:
1 由于是中序遍历,所以next node应该在given node(n)的右边;
2 右子树的哪个元素呢?应该是右子树最早访问的那个,即:右子树最左边的一个;
3 如果n没有右子树,怎么办?应该找到n的parent,叫做q;
3.1 如果n在q左边->直接返回q;
3.2 如果n在q右边(说明q已经被完整遍历)->应该找q的parent(x),x应该没有完整遍历;
如何得知x是否被完整遍历过?
当我们从左节点到父节点时,左节点被完整遍历了,但是父节点没有;
伪代码:
Node inorderSucc(Node n){
if(n has a right subtree)
{
return leftmost child of right subtree
}
else//没有右子树,找n的父节点q
{
if(n in left of q)
{
return q
}
else if(n in right of q)
{
n=n.parent;
}
}
}
TreeNode inorderSuccess(TreeNode n)
{
if (n == null) return null;
//如果有右子树->返回右子树的最左元素;
if (n.right != null)
return leftMostChild(n.right);
else
{
TreeNode q = n;
TreeNode x = q.parent;
//向上,直到x的左边不是q
while (x != null && x.left != q)
{
q = x;
x = x.parent;
}
//n在q左边->返回q
return x;
}
}
TreeNode leftMostChild(TreeNode n)
{
if (n == null)
return null;
while (n.left != null)
n = n.left;
return n;
}
小结:
面对复杂的问题,最好先写伪代码/画图,再写代码。有助于理清思路