我创建了一个包含类节点的程序,用于表示任何类型(模板)的二叉树。程序设置二叉树,打印并搜索 - 节点类C++
在我的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;
}
我改变了我的代码,这样的构造,现在将它们设置为NULL模板 节点 ::节点(T我,节点 * LFT,节点 * RHT){ 项目=我; left = NULL; right = NULL; } 这是你的意思吗? –
Liam
@Liam - 是的;我建议初始化列表中的值(对不起:现在忘了':';现在更正),但你的更正应该足够了。 – max66
程序现在执行时没有崩溃,但不打印任何值 – Liam