本文介绍了从现有树中创建一棵左右的新树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码类似于中给出的代码。

My code is similar to the one given in this thread.

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;
    }
}

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

In my main program, there a need for this:

我有两棵树:

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

我需要创建一个新的树:

I need to create a new tree with:

根作为T的对象,left = tree1和right = tree2;

root as an object of T and left = tree1 and right = tree2;

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

To do this I tried to add this constructor:

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

并尝试从主打电话:

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

我明白这不行,但该怎么办?

I understand this won't work but what should I do?

编译错误

错误C2664:'BinarySearchTree :: BinarySearchTree(const T& BinarySearchTree :: tree_node *,BinarySearchTree :: tree_node *)':不能将参数2从BinarySearchTree *转换为BinarySearchTree :: tree_node *

error C2664: 'BinarySearchTree::BinarySearchTree(const T &,BinarySearchTree::tree_node *,BinarySearchTree::tree_node *)' : cannot convert parameter 2 from 'BinarySearchTree *' to 'BinarySearchTree::tree_node *'

推荐答案

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

First of all: your call of the constructor is not correct, it should be like this:

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

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

I would suggest, to implement a so called copy constructor, a constructor, taking an instance of the same class as argument:

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

从子节点创建一个新树。

this would let you create a new tree from a child node.

我希望我已经回答了你的问题,随时问是否有什么不够清楚! :)

I hope I have answered your question, feel free to ask if anything is not clear enough! :)

这篇关于从现有树中创建一棵左右的新树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 08:33