将STL列表转换为二进制搜索树递归模板

Converting STL List to a Binary Search Tree Recursion Template

本文关键字:搜索树 递归 二进制 STL 列表 转换      更新时间:2023-10-16

以下是我迄今为止所拥有的:

#include <stdio.h>
#include "bintree.h"
#include <list>
#include <iostream>
using namespace std;
using namespace main_savitch_10;
template <class Item>
binary_tree_node<Item>* convert(list<Item> *& list, int start, int end);
template <class Item> 
binary_tree_node<Item>* convert(list<Item> *head, int n);
int main(int argc, char **argv)
{
    list<int> L;
    L.push_front(10);
    L.push_back(20);
    L.push_back(30);
    L.push_back(40);
    L.push_back(50);
    L.push_back(60);
    L.push_back(70);
    list<int>::iterator test;
    for(test = L.begin(); test != L.end(); test++)
    {
    cout<<*test<<" ";
    }
    binary_tree_node<int>* L2 = convert(L, 7);
    print(L2, 3);
}
template <class Item>
binary_tree_node<Item>* convert(list<Item> *& list, int start, int end)
{
    if (start > end) return NULL;
    int mid = start + (end - start) / 2;
    binary_tree_node<Item>* leftChild = convert(list, start, mid-1);
    binary_tree_node<Item>* parent = new binary_tree_node<Item> (list->data());
    parent->left() = leftChild;
    list = list->next();
    parent->right() = convert(list, mid+1, end);
    return parent;
}
template <class Item> 
binary_tree_node<Item>* convert(list<Item> *head, int n) 
{
    return convert(head, 0, n-1);
}

我在线路上出错binary_tree_node<int>* L2 = convert(L, 7);

说调用没有匹配函数。。。当我把它们列在主菜单的正上方时,这怎么可能呢?

附带说明:"bintree.h"和命名空间main_savitch_10来自二进制搜索树的模板实现文件,可以在http://ksuweb.kennesaw.edu/~dgayler/cs3304/text_examples/chap10/bintree.hhttp://ksuweb.kennesaw.edu/~dgayler/cs3304/text_examples/chap10/bintree.template

您的函数使用一个指向列表的指针。这意味着您应该将列表的地址传递给它。

如果我看看这个:

template <class Item> 
binary_tree_node<Item>* convert(list<Item> *head, int n) 

然后在这个:

binary_tree_node<int>* L2 = convert(L, 7);

然后在这个:

list<int> L;

我可能错了,但L不是指针,你在调用中没有使用它的地址,定义需要一个指针。