问题
例子
思路
-
方法1

-
方法2
1: 如果该结点有右子树,则返回右子树最深的左子树

2:如果该结点没有右子树,不断向上找该结点的父结点。
2.1:如果存在某个父节点,是其父节点的左子树,则返回其父节点

2.2:如果不存在某个父节点,是其父节点的左子树,则返回null

代码
//方法1
import java.util.*;
public class Solution {
private TreeLinkNode res = null;
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
TreeLinkNode node = pNode;
while(node.next!=null) {
node = node.next;
}
TreeLinkNode root=node;
midOrder(root,pNode);
return res;
}
public void midOrder(TreeLinkNode root, TreeLinkNode node) {
if(root==null) return;
if(root.left!=null) midOrder(root.left,node);
if(root!=node && node.val<=root.val) {
//只找第一个满足条件的,此时res为null
if(res==null) {
res=root;
}
return;
}
if(root.right!=null) midOrder(root.right,node);
}
}
//方法2
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
if(pNode==null) return null;
if(pNode.right!=null) {
TreeLinkNode node = pNode.right;
while(node.left!=null) {
node=node.left;
}
return node;
}
while(pNode.next!=null) {
if(pNode.next.left==pNode) return pNode.next;
pNode = pNode.next;
}
return null;
}
}
二叉树中继节点查找算法
本文介绍了一种在二叉树中寻找指定结点后续节点的有效算法,提供了两种方法实现这一目标:一是通过遍历右子树找到最深的左子节点;二是当结点无右子树时,回溯至首个父节点作为左子树的结点。通过具体实例和代码演示了算法的执行流程。

576

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



