描述
设计一个算法,给定一个二叉树中的节点,返回它的后继节点。该二叉树的节点有父节点引用。
分析
二叉树结点的后继一般指的是中序遍历中,该结点的后一个结点。
如果二叉树的节点是没有父节点的引用的。那么对二叉树进行中序遍历可以很容易拿到指定节点的后继节点。
现在二叉树的节点拥有父节点的引用,也就是说访问二叉树时不需要使用栈就可以轻松回溯,解决此问题的效率会高很多。时间复杂度仅为 O(logN)。
步骤
如果指定节点有右子树,那么该节点的后继节点一定是右子树中最左边的节点。
如果指定节点没有右子树,则往上找它的父节点。直到当前节点是它的父节点的左孩子,那么这个父节点就是后继节点。
代码
class FindSuccessorNode {
public static Node findSuccessorNode(Node node) {
if (node != null) { // 空节点
if (node.right != null) { // 如果该节点有右子树,则找到右子树最左的节点
Node tmp = node.right;
while (tmp.left != null) {
tmp = tmp.left;
}
return tmp;
} else { // 如果该节点没有右子树,则找它的父节点。直到找到一个节 点是其父节点的左儿子,则返回这个父节点
if (node.parent != null) {
Node tmp = node.parent;
while (tmp.parent != null) {
if (tmp.parent.left == tmp)
return tmp.parent;
}
throw new RuntimeException("该节点没有后继");
} else {
throw new RuntimeException("该节点没有后继");
}
}
}
throw new RuntimeException("该节点没有后继");
}
// 带有父节点引用的 Node 类
static class Node {
public int element;
public Node left;
public Node right;
public Node parent;
public Node (int x) {
this(x, null, null, null);
}
private Node(int x, Node right, Node left, Node parent) {
this.element = x;
this.right = right;
this.left = left;
this.parent = parent;
}
}
public static void main(String[] args) {
// 建树
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
n1.left = n2;
n1.right = n3;
n2.parent = n1;
n2.left = n4;
n2.right = n5;
n3.parent = n1;
n4.parent = n2;
n5.parent = n2;
// 寻找节点 n5 的后继
int x = findSuccessorNode(n5).element;
System.out.println(x);
}
}
3万+




被折叠的 条评论
为什么被折叠?



