0

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:

BinaryTree.cpp:26: parse error before 'new
BinaryTree.cpp:31: parse error before ';'

....etc etc... any ideas?

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

3 Answers 3

3

new is a C++ keyword. You mustn't use it as an identifier (e.g. 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.

Sign up to request clarification or add additional context in comments.

Comments

3

new is keyword in c++ and You can't name variable with that word so

node *new = new node;

is illegal

Comments

3

new is a reserved word, you cannot use it as a variable name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.