我尝试用他的搜索,插入和删除功能来编程二叉树 但主要是编译器无法识别在头文件中声明并初始化的“found”和“root”在构造函数中 下面的代码二叉树:无法识别的节点
binarytree.cpp
#include <iostream>
#include <cstddef>
#include "Tree.h"
using namespace std;
int main() {
Tree a;
char c;
while(c!='4'){
cout<<"Inserisci 1 per inserire un valore nell'albero\n 2 per cercarne un valore\n";
cout<<"3 per distruggere un valore e tutti i suoi rami\n 4 per uscire";
cin>>c;
if(c=='1'){
int n;
cout<<"Inserisci il valore numerico da immettere";
cin>>n;
a.insert(n,a.root);
}
if(c=='2'){
int n;
cout<<"Inserisci il valore numerico da cercare";
cin>>n;
a.search(n,a.root,a.found);
if(a.found==NULL)
cout<<"Elemento non trovato";
}
if(c=='3'){
int n;
cout<<"Inserisci il valore numerico da eliminare con tutti i suoi rami";
cin>>n;
a.search(n,a.root,a.found);
if(a.found==NULL)
cout<<"Elemento non trovato";
a.destroy_tree(a.found);
}
}
return 0;
}
tree.h中
#ifndef TREE_H_
#define TREE_H_
#include <cstddef>
class Tree {
private:
struct node{
node *right;
node *left;
int data;
};
public:
Tree(){
root = NULL;
found = NULL;
}
void destroy_tree(node*);
void insert(int, node*);
void search(int, node*,node*);
node *root;
node *found;
};
#endif /* TREE_H_ */
Tree.cpp
#include "Tree.h"
#include <cstddef>
void Tree::destroy_tree(node *leaf){
if(leaf!=NULL){
Tree::destroy_tree(leaf->left);
Tree::destroy_tree(leaf->right);
delete leaf;
}
}
void Tree::insert(int key, node *leaf){
if(leaf==NULL)
leaf->data=key;
else{
if(key<leaf->data)
{
if(leaf->left!=NULL)
insert(key, leaf->left);
else
{
leaf->left = new node;
leaf->left->data=key;
leaf->left->left=NULL; //Sets the left child of the child node to null
leaf->left->right=NULL; //Sets the right child of the child node to null
}
}
else if(key>=leaf->data)
{
if(leaf->right!=NULL)
insert(key, leaf->right);
else
{
leaf->right=new node;
leaf->right->data=key;
leaf->right->left=NULL; //Sets the left child of the child node to null
leaf->right->right=NULL; //Sets the right child of the child node to null
}
}
}
}
void Tree::search(int key, node *leaf, node* found){
if(leaf!=NULL){
if(key==leaf->data)
found = leaf;
if(key<leaf->data)
search(key, leaf->left, found);
else
search(key, leaf->right, found);
}
else found = NULL;
}
预先感谢
对于**不**使用明确的'root'指针变量的问题(和答案)请参阅http://stackoverflow.com/questions/30326969/i-would-like-not-to-use-root-as -global/ – CiaPan