前驱节点(predecessor)
- 前驱节点:中序遍历时的前一个节点。
- 如果是二叉搜索树,前驱节点就是前一个比它小的节点。

node.left != null
举例:6、13、8predecessor = node.left.right.right.right...
,终止条件:right为nullnode.left == null && node.parent != null
,举例:7、11、9、1predecessor = node.parent.parent.parent...
终止条件:node在parent的右子树中node.left == null && node.parent == null
,那就没有前驱节点,举例:没有左子树的根节点
private static class Node<E>{E element;Node<E> left;Node<E> right;Node<E> parent;public Node(E element,Node<E> parent) {this.element = element;this.parent = parent;}
}
private Node<E> predecessor(Node<E> node){if(node == null) return null;Node<E> p = node.left;if (node.left != null) {while (p.right != null) {p = p.right;}return p;}while (node.parent != null && node == node.parent.left) {node = node.parent;}return node.parent;
}
后继节点(successor)
- 后继节点:中序遍历时的后一个节点。
- 如果是二叉搜索树,后继节点就是后一个比它大的节点。

node.right != null
,举例:1、8、4successor = node.right.left.left.left...
终止条件:left为nullnode.right == null && node.parent != null
,举例:7、6、3、11successor = node.parent.parent.parent...
,终止条件:node在parent的左子树中node.right = null && node.parent == null
,那就没有后驱节点,举例:没有右子树的根节点。
private static class Node<E>{E element;Node<E> left;Node<E> right;Node<E> parent;public Node(E element,Node<E> parent) {this.element = element;this.parent = parent;}
}
private Node<E> successor(Node<E> node){if(node == null) return null;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;
}