gpt4 book ai didi

java - 如何使用java为二叉搜索树创建深度复制

转载 作者:行者123 更新时间:2023-11-30 04:07:16 29 4
gpt4 key购买 nike

public class BinarySearchTree
{
public class TreeNode
{
private int item;
private TreeNode leftLink;
private TreeNode rightLink;
// One constructor for TreeNode
///////////////////////////////////////////////////////
public TreeNode(int newItem, TreeNode left, TreeNode right)
{
item = newItem;
leftLink = left;
rightLink = right;
}
} // End of TreeNode inner class

// Declaration of class BinarySearchTree begins here.
// Three instance variables.
private TreeNode root;
private TreeNode parent; // parent node of a target node being sought
private int parentLink; // pointer number of a parent node being sought


public BinarySearchTree( )
{
root = parent = null;
parentLink = 0; // no such pointer at the beginning
}

我想要这棵树的深拷贝,标题应与下面给出的相同,它应该像描述的那样工作,此构造函数将创建一棵二叉搜索树,它是由此构造函数的单独参数给出的现有二叉搜索树的深拷贝。

public BinarySearchTree (BinarySearchTree  bst)
{

//your code should be here
}
// more codes here but given code is ok for question
}

最佳答案

您可以向 TreeNode 添加一个函数:

public TreeNode deepCopy() {
return new TreeNode(item, leftLink.deepCopy(), rightLink.deepCopy())
}

然后:

public BinarySearchTree (BinarySearchTree  bst) {
root = bst.root.deepCopy();
parent = bst.parent.deepCopy();
parentLink = bst.parentLink;
}

当然这是一个例子,你应该注意null值。

您可以在这里找到更好的示例:How to deep copy a tree?

关于java - 如何使用java为二叉搜索树创建深度复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20443969/

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