我創建了一個包含類節點的程序,用於表示任何類型(模板)的二叉樹。程序設置二叉樹,打印並搜索 - 節點類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