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

时间:2016-03-23 16:01:29

标签: c++ recursion stl

这是我到目前为止所做的:

#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.h http://ksuweb.kennesaw.edu/~dgayler/cs3304/text_examples/chap10/bintree.template

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

如果我看这个:

var gameScore = PFObject(className:"GameScore")
gameScore["score"] = 1337
gameScore["playerName"] = "Sean Plott"
gameScore.saveInBackgroundWithBlock {
  (success: Bool, error: NSError?) -> Void in
  if (success) {
    // The object has been saved.
  } else {
    // There was a problem, check error.description
  }
}

然后在此:

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

然后在此:

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

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