[英]Node Class to represent a binary tree C++
我創建了一個node.h類,定義了一個稱為node的類,用於表示二叉樹(任何類型)。 似乎是構造函數無法正常工作。 錯誤如下:我只是開始在此類之內編寫構造函數,而這是我第一次遇到二進制樹。 誰能為我指出正確的方向,以解決這些錯誤並使我的代碼正常工作? 謝謝。
節點
#ifndef NODE_H
#define NODE_H
#include <iostream>
//an object of type node holds 3 things
// - an item (oftype 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:
//..
};
//constructor
template<typename T>
Node<T>::Node(T i, Node<T> *l, Node<T> *r) {
item = i;
lft = NULL;
rht = NULL;
}
//constructor //is this correct?
template <typename T>
Node<T>::Node(T i) { //should i be a parameter here?
item = i; //is this right?
}
//destructor
template <typename T>
Node<T>::~Node() {
delete left;
delete right;
//delete;
}
//print tree method
template <typename T>
void Node<T>::printTree() {
if (lft != NULL) {
lft->printTree();
cout << item << endl;//alphabetical order
}
if (rht != NULL) {
rht->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")));
}
int main() {
Node<string> *s_tree;
s_tree = setUpTree();
cout << "Part 2 :Priting tree vals " << endl << endl;
s_tree->printTree();
cout << endl;
//search for range of tree values
//searchTree(s_tree, "Sunday");
//searchTree(s_tree, "Monday");
return 0;
}
沒有在構造函數和其他方法中使用的成員聲明。 編譯器不知道“ rht
或“ right
含義。 從您的代碼來看,該類應該看起來像這樣:
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:
Node* left;
Node* right;
T item;
//private data member functions:
//..
};
因此,現在編譯器知道left
, right
和item
含義。 現在,您可以在該類的成員函數中使用這些標識符。 請注意,編譯器仍然不知道rht
或lft
是什么,因此應將它們替換為right
和left
。
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.