gpt4 book ai didi

java - 如何在不使用父引用节点的情况下在二叉树中找到光标的父节点

转载 作者:太空宇宙 更新时间:2023-11-04 12:05:06 24 4
gpt4 key购买 nike

我正在尝试将光标移动到二叉树中的父节点。我想递归地执行此操作,而不使用保留节点来跟踪父级。我认为我的基本/停止情况是正确的,但我相信最后两个 if 语句是错误的。我不确定该怎么做。任何建议都会有所帮助。谢谢。

   public void cursorToParent()
{
TreeNode parent = root;
if(cursor == root )
return;
if(parent.getLeft().equals(cursor) || parent.getRight().equals(cursor) )
cursor = parent;
else
if(parent.getLeft()!=null)
{
parent = parent.getLeft();
cursorToParent();
}
if(parent.getLeft()!=null)
{
parent = parent.getLeft();
cursorToParent();
}

}

最佳答案

需要将当前处理节点传递给该方法。因此必须有一个方法 cursorToParentImpl() ,它将从前一个方法中使用 root 调用:

public boolean cursorToParentImpl(TreeNode current)
{
if(cursor == current )
return false;
if(current.getLeft () == cursor || current.getRight() == cursor) {
cursor = current;
return true;
}
else { // note the missing parenthesis too
if(current.getLeft()!=null) {
if (cursorToParentImpl(current.getLeft()))
return true;
}
if(current.getRight()!=null) {
if (cursorToParentImpl(current.getRight()))
return true;
}
}
return false;
}

并称其为:

public void cursorToParent()
{
if (cursor == root)
return;
cursorToParentImpl(root);
}

此外,您可以避免调用 equals() 并仅使用 == 运算符,因为这里它应该比较对节点的引用。

关于java - 如何在不使用父引用节点的情况下在二叉树中找到光标的父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40458223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com