从现有树创建新树(左和右)

creating a new tree from the existing trees as left and right

本文关键字:新树 创建      更新时间:2023-10-16

我的代码与此线程中给出的代码类似。

template<class T> 
class BinarySearchTree
{
private:
    struct tree_node
    {
        tree_node* left;
        tree_node* right;
        T data;
        tree_node( const T & thedata, tree_node * l = NULL, tree_node * r = NULL )
                : data( thedata ), left( l ), right( r ) { }
    };
    tree_node* root;
public:
    BinarySearchTree()
    {
        root = NULL;
    }
}

在我的主程序中,需要这样做:

我有两棵树:

BinarySearchTree<T> tree1;
BinarySearchTree<T> tree2;

我需要创建一个新树:

根作为 T 的对象,左 = 树 1,右 = 树 2;

为此,我尝试添加此构造函数:

BinarySearchTree(const T& x, tree_node* l, tree_node* r); 

并尝试从主调用:

BinarySearchTree<T> newTree(T object,tree1,tree2);

我知道这行不通,但我该怎么办?

编译错误

错误 C2664: '二进制搜索树::二进制搜索树(常量 T &,二进制搜索树::tree_node *,二进制搜索树::tree_node *

)' : 无法将参数 2 从"二进制搜索树 *"转换为"二进制搜索树::tree_node *"

首先:你对构造函数的调用不正确,应该是这样的:

BinarySearchTree<T> newTree(object,tree1,tree2);

我建议,实现一个所谓的复制构造函数,一个构造函数,将同一类的实例作为参数:

BinarySearchTree(const BinarySearchTree& other)
{
    root = other.root; // propably you have to allocate it with "new"
}

这将允许您从子节点创建新树。

我希望我已经回答了你的问题,如果有什么不够清楚的地方,请随时问! :)

在实现您在这里尝试实现的目标后,您将遇到许多问题。首先,在连接树之后,您希望在根节点上存储的内容是最重要的,在许多情况下,生成的树不会是二叉搜索树。只需传递对指针的引用或指向树根节点指针的指针即可解决此编译器问题。

void Join(const T & thedata, tree_node *& l, tree_node &* r );

如果你用 * 定义你的函数参数,这说明编译器他们期望一个指向对象的指针。如果这样做,则必须给出对象的地址,而不是对象本身,例如:

BinarySearchTree<T> newTree(object,&tree1, &tree2);

您可以更改调用方法的方式,也可以更改方法定义以接受引用,就像使用 const T& 一样。