clllll  

在二叉树中找到一个节点的后继节点

二叉树节点多了个属性 parent

public static class NewNode {
public int value;
public NewNode left;
public NewNode right;
public NewNode parent;
public NewNode(int val) {
value = val;
}
}

头节点的parent指向null
在二叉树的中序遍历中,node 的下一个节点就是node的后继节点

第一种,中序遍历,保存在数组中。太low

第二种,利用parent指针, 分俩大类情况

1)当前节点没有右子树,然后直到 某个节点是父节点的左孩子。那么它的后继节点就是 当前父节点

2)当前节点有右子树,右子树最左的node就是他的后继节点。

public static NewNode findNextNode(NewNode newNode) {
if (newNode == null) {
return null;
}
if (newNode.right != null) {
// 有右子树的情况, 右子树最左的节点,
return findLeftNewNode(newNode.right);
} else {
// 没有右孩子
// 往上 找到直到 某个节点是自己父亲的左孩子
while (newNode.parent != null) {
if (newNode.parent.left == newNode) {
return newNode.parent;
}
newNode = newNode.parent;
}
}
return null;
}
public static NewNode findLeftNewNode(NewNode newNode) {
while (newNode.left != null) {
newNode = newNode.left;
}
return newNode;
}
posted on   llcl  阅读(137)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
 
点击右上角即可分享
微信分享提示