二进制搜索树无法正常工作? (解析错误)

时间:2011-11-29 19:36:27

标签: c++ binary-tree binary-search-tree parse-error

我的代码中出现了解析错误。我可能错过了一些愚蠢的东西......但是在盯着它之后,我无法弄清楚出了什么问题。错误从第26行开始:

BinaryTree.cpp:26:解析之前的错误 BinaryTree.cpp:31:在';'

之前解析错误

....等等......任何想法?

#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;
}

3 个答案:

答案 0 :(得分:3)

new是c ++中的关键字,你不能用这个词命名变量

node *new = new node;

是非法的

答案 1 :(得分:3)

newreserved word,您不能将其用作变量名称。

答案 2 :(得分:3)

new是一个C ++关键字。您不得将其用作标识符(例如变量名称)。

无论如何,你的构造函数会更好:

BinaryTree::BinaryTree(int data) : root(new node) { /* ... */ }

使用unique_ptr<Node> s,整个班级可能会更好。