【发布时间】:2017-04-30 01:58:30
【问题描述】:
我创建了一个包含类节点的程序,用于表示任何类型的二叉树(模板)。
在我的 Node.h 类中,我有两个构造函数,但是我不确定我是否正确实现了它们。在构造函数中初始化值让我感到困惑。在我的 main.cpp 文件中,我有一个 setUpTree 函数。我的程序现在执行,但不打印设置的树。
我已经尝试了几个小时试图解决这个问题,但没有结束。我还没有真正体验过 C++、指针、构造函数等。
如果有人能帮我修复我的代码以便 setUpTree 函数和 printTree 方法正常工作,我将不胜感激。
谢谢
Node.h 类:
#ifndef NODE_H
#define NODE_H
#include <iostream>
#include <string>
using namespace std;
//an object of type node holds 3 things
// - an item (of type t)
// - a left subtree
// - a right subtree
template<typename T>
class Node {
public:
Node(T item); //constructor to create a leaf node
Node(T item, Node *lft, Node *rht); //constructor which creates an internal node
~Node(); //Destructor
//public data member functions:
bool searchTree(T key);
void printTree();
private:
//private data member functions:
Node* left;
Node* right;
T item;
};
//constructor
template<typename T>
Node<T>::Node(T i, Node<T> *lft, Node<T> *rht) {
item = i;
left = NULL;
right = NULL;
}
//constructor
template <typename T>
Node<T>::Node(T i) { //should i be a parameter here?
item = i; //is this right for this constructor?
}
//destructor
template <typename T>
Node<T>::~Node() {
delete left;
delete right;
//delete;
}
//print tree method
template <typename T>
void Node<T>::printTree() {
if (left != NULL) {
left->printTree();
cout << item << endl;//alphabetical order
}
if (right != NULL) {
right->printTree();
//cout << item << endl; //post order
}
}
//search Tree method
template <typename T>
bool Node<T>::searchTree(T key) {
bool found = false;
if (item == key) {
return true;
}
if (left != NULL) {
found = left->searchTree(key);
if (found) return true;
}
if (right != NULL) {
return right->searchTree(key);
}
return false; //if left and right are both null & key is not the search item, then not found == not in the tree.
}
#endif
Main.cpp 类:
#include "Node.h"
#include <iostream>
using namespace std;
//set up tree method
Node<string> *setUpTree() {
Node<string> *s_tree =
new Node<string>("Sunday",
new Node<string>("monday",
new Node<string>("Friday"),
new Node<string>("Saturday")),
new Node<string>("Tuesday",
new Node<string>("Thursday"),
new Node<string>("Wednesday")));
return s_tree;
}
int main() {
Node<string> *s_tree;
s_tree = setUpTree(); //call setUpTree method on s_tree
cout << "Part 2 :Printing tree values: " << endl;
s_tree->printTree(); //call print tree method
cout << endl;
//search for range of tree values
//searchTree(s_tree, "Sunday");
//searchTree(s_tree, "Monday");
return 0;
}
【问题讨论】:
标签: c++ templates constructor binary-tree nodes