1.前驱节点:中序遍历时的前一个节点
如果是二叉搜索树,前驱节点就是前一个比它小的节点,即肯定是左子树的部分
- 1.node.left != null,则其前驱节点是左子树中的最大那个,即左子树的右孩子的右孩子…right == null
- 2.node.left == null &&node.parent != null,那么其前驱节点是其父节点的父节点,直到需要考虑的节点已经为parent的右子树
- 3.node.leftnull== && node.parent ==null,则没有前驱节点为空
protected Node<E> predecessor(Node<E> node) {
if (node == null) return null;
// 前驱节点在左子树当中(left.right.right.right....)
Node<E> p = node.left;
if (p != null) {
while (p.right != null) {
p = p.right;
}
return p;
}
// 从父节点、祖父节点中寻找前驱节点
// 考虑父节点不为空 且 该节点为父节点的左子树
while (node.parent != null && node == node.parent.left) {
node = node.parent;
}
/**
* 不符合的时候是以下两种情况
* node.parent == null---->返回null
* node == node.parent.right---->返回父节点即node.parent
* 所以返回 node.parent
*/
return node.parent;
}
2.后继节点:中序遍历时的后一个节点
如果是二叉搜索树,后继节点就是后一个比它大的节点,即肯定是右子树的部分,即前驱节点左取右,右取左即可
protected Node<E> successor(Node<E> node) {
if (node == null) return null;
// 前驱节点在左子树当中(right.left.left.left....)
Node<E> p = node.right;
if (p != null) {
while (p.left != null) {
p = p.left;
}
return p;
}
// 从父节点、祖父节点中寻找后继节点
while (node.parent != null && node == node.parent.right) {
node = node.parent;
}
return node.parent;
}