方法一:
如果node的定义有parent reference
就非常直接:
public static BTNode inorderSucc(BTNode e) {
if (e != null) {
BTNode p;
// Found right children -> return 1st inorder node on right
if (e.parent == null || e.right != null) {
p = leftMostChild(e.right);
} else {
// Go up until we’re on left instead of right (case 2b)
while ((p = e.parent) != null) {
if (p.left == e) {
break;
}
e = p;
}
}
return p;
}
return null;
}
public static BTNode leftMostChild(BTNode e) {
if (e == null) {
return null;
}
while (e.left != null) {
e = e.left;
}
return e;
}
如果没有也没关系
加一个
/*感谢崔大神对我这个findParent method做了非常直观有效的改进*/
BTNode findParent(BTNode cur, BTNode n) {
if (cur == null) {
return null;
}
if (cur.left == n || cur.right == n) {
return cur;
}
BTNode father = findParent(cur.left, n);
if (father != null) {
return father;
}
return findParent(cur.right, n);
}
用来找到parent node即可
方法2:这个方法比较耍赖了,就是直接将BST转化成inorder排列的Queue
显然succ就是queue中某点的后面一点。
public void toQueue(Queue<BTNode> q) {
if (root == null) {
return;
} else {
toQueue2(root, q);
while (!q.isEmpty()) {
customer c = (customer) q.dequeue().item;
System.out.println(c.toString());
}
}
}
void toQueue2(BTNode cur, Queue<BTNode> q) {
if (cur == null) {
return;
}
toQueue2(cur.left, q);
q.enqueue(cur);
toQueue2(cur.right, q);
}
如果node的定义有parent reference
就非常直接:
public static BTNode inorderSucc(BTNode e) {
if (e != null) {
BTNode p;
// Found right children -> return 1st inorder node on right
if (e.parent == null || e.right != null) {
p = leftMostChild(e.right);
} else {
// Go up until we’re on left instead of right (case 2b)
while ((p = e.parent) != null) {
if (p.left == e) {
break;
}
e = p;
}
}
return p;
}
return null;
}
public static BTNode leftMostChild(BTNode e) {
if (e == null) {
return null;
}
while (e.left != null) {
e = e.left;
}
return e;
}
如果没有也没关系
加一个
/*感谢崔大神对我这个findParent method做了非常直观有效的改进*/
BTNode findParent(BTNode cur, BTNode n) {
if (cur == null) {
return null;
}
if (cur.left == n || cur.right == n) {
return cur;
}
BTNode father = findParent(cur.left, n);
if (father != null) {
return father;
}
return findParent(cur.right, n);
}
用来找到parent node即可
方法2:这个方法比较耍赖了,就是直接将BST转化成inorder排列的Queue
显然succ就是queue中某点的后面一点。
public void toQueue(Queue<BTNode> q) {
if (root == null) {
return;
} else {
toQueue2(root, q);
while (!q.isEmpty()) {
customer c = (customer) q.dequeue().item;
System.out.println(c.toString());
}
}
}
void toQueue2(BTNode cur, Queue<BTNode> q) {
if (cur == null) {
return;
}
toQueue2(cur.left, q);
q.enqueue(cur);
toQueue2(cur.right, q);
}