什么是后继?
中序遍历中一个结点的下一个结点,就是后继结点。
比如:4251367中 4的后继是2 2的后继是5 只有7的后继是null
二叉树的创建增加了一个指向父结点的pointer
public static class Node {
int val;
Node left;
Node right;
Node parent; //父结点
public Node(int val, Node left, Node right) {
this.val = val;
this.left = left;
this.right = right;
}
}
求后继又两种判断条件
情况一:x结点有右树的时候,x结点的后继是它右树的最左结点
情况二:x结点无右树的时候,x结点向上找父亲并判断是不是父亲的左孩子,如果是返回父亲,不是继续向上找父亲
public static Node getSuccessorNode(Node node) {
if (node == null) {
return node;
}
if (node.right != null) {//有右孩子
return getLeftMost(node.right);
} else { //无右孩子
Node parent = node.parent;
//循环判断条件:当parent等于null也就是所以孩子都不是父亲的左孩子,head结点就是当前结点的左孩子,或者找到了孩子是父亲的左孩子
while (parent != null && parent.left != node) {
node = parent;
parent = node.parent;
}
return parent;
}
}
private static Node getLeftMost(Node node) {
if (node == null) {
return null;
}
while (node.left != null) {
node = node.left;
}
return node;
}