[英]Binary Search Tree not working properly? (parse errors)
I'm getting parse errors in my code. 我在我的代码中解析错误。 I'm probably missing something silly.. but after staring at it, I can't figure out what's wrong. 我可能想念一些愚蠢的东西..但盯着它看,我不知道出了什么问题。 The errors start at line 26: 错误从第26行开始:
BinaryTree.cpp:26: parse error before 'new BinaryTree.cpp:26:在“新建”之前解析错误
BinaryTree.cpp:31: parse error before ';' BinaryTree.cpp:31:分析“;”之前的错误
....etc etc... any ideas? .... etc等...有什么想法吗?
#include <cstdlib>
#include <iostream>
using namespace std;
class BinaryTree{
struct node{
int data;
node *left;
node *right;
};
node *root;
public:
BinaryTree(int);
void addNode(int);
void inorder();
void printInorder(node);
int getHeight();
int height(node);
};
BinaryTree::BinaryTree(int data){
node *new = new node;
new->data = data;
new->left = NULL;
new->right = NULL;
root = new;
}
void BinaryTree::addNode(int data){
node *new = new node;
new->data = data;
new->left = NULL;
new->right = NULL;
node *current;
node *parent = NULL;
current = root;
while(current){
parent = current;
if(new->data > current->data) current = current->right;
else current = current->left;
}
if(new->data < parent->data) parent->left = new;
else parent->right = new;
}
void BinaryTree::inorder()
printInorder(root);
}
void BinaryTree::printInorder(node current){
if(current != NULL){
if(tree->left) printInorder(tree->left);
cout<<" "<<tree->data<<" ";
if(tree->right) printInorder(tree->right);
}
else return;
}
int BinaryTree::getHeight(){
return height(root);
}
int BinaryTree::height(node new){
if (new == NULL) return 0;
else return max(height(new->left), height(new->right)) + 1;
}
int main(int argCount, char *argVal[]){
int number = atoi(argVal[1]);
BinaryTree myTree = new BinaryTree(number);
for(int i=2; i <= argCount; i++){
number = atoi(argVal[i]);
myTree.addNode(number);
}
myTree.inorder();
int height = myTree.getHeight();
cout << endl << "height = " << height << endl;
return 0;
}
new is keyword in c++ and You can't name variable with that word so new是c ++中的关键字,因此您无法使用该单词命名变量,因此
node *new = new node;
is illegal 是非法的
new
是保留字 ,您不能将其用作变量名。
new
is a C++ keyword. new
是C ++关键字。 You mustn't use it as an identifier (eg variable name). 您不得将其用作标识符(例如,变量名)。
In any event, your constructor would be better off as: 无论如何,您的构造函数会更好:
BinaryTree::BinaryTree(int data) : root(new node) { /* ... */ }
And your class as a whole would probably be better off with unique_ptr<Node>
s. 整个类最好使用unique_ptr<Node>
更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.