什么是后继节点
二叉树的后继节点是指在中序遍历中,某节点的下一个节点。
以下是二叉树后继节点的定义:
- 如果当前节点没有右子树,则后继节点就是该节点的左子树的最左下角的节点。
- 如果当前节点有右子树,则后继节点是该节点右子树中的最左下角节点。
题目介绍
根绝一个特殊结构的二叉树,找出节点的后继节点,把时间复杂度降到O(k)k代表节点到后继节点的实际距离
二叉树结构定义
public class Node {
public int value;
public Node left;
public Node right;
public Node parent;
public Node(int data) {
this.value = data;
}
}
代码
public static Node getSuccessorNode(Node node) {
if (node == null) {
return node;
}
//如果有右子树 就取右子树的最左子节点
if (node.right != null) {
return getLeftMost(node.right);
} else { // 无右子树
Node parent = node.parent;
//两种情况,如果当前节点不是父节点的有节点那么父节点就是后继节点,
//如果是右节点,那么要一直向上找可能为null 或者一直到不是右节点时的父节点
while (parent != null && parent.right == node) { // 当前节点是其父亲节点右孩子
node = parent;
parent = node.parent;
}
return parent;
}
}
public static Node getLeftMost(Node node) {
if (node == null) {
return node;
}
while (node.left != null) {
node = node.left;
}
return node;
}