在二叉树中的中序遍历中,node节点的后一个节点叫做node的后继节点。
在常规的二叉树中,直接按照中序遍历走一遍。
如果二叉树中每个节点多了一个parent属性,那么时间复杂度便可以下降很多。
1.如果这个节点存在右子树,那么这个节点的后继节点就是右子树的最左节点。
2.如果这个节点没有右子树,那么这个节点的后继节点就是它的第一个祖先节点的父节点(这个祖先节点要是它父节点的左孩子)

也就是说x 的后继节点就是y,对于Y来说x就是它左子树的最后一个节点。遍历完左子树接着就是遍历Y。
3.最右下角的那个节点是没有后继节点的
public static Node getSuccessorNode(Node node) {
if(node == null) {
return node;
}
//如果存在右节点,就只需要找右树的最左节点
if(node.right!=null) {
return getLeftMost(node);
}
//如果不存在右节点
else {
Node parent = node.parent;
while(parent!=null && parent.left!=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;
}
本文探讨了在二叉树中引入parent属性后,如何通过中序遍历快速找到节点的后继节点,包括右子树最左节点和祖先节点的情况,以及相关算法实现。
1645

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



