【问题标题】:Binary Search Tree not working properly? (parse errors)二叉搜索树不能正常工作? (解析错误)
【发布时间】:2011-11-29 19:36:27
【问题描述】:

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

BinaryTree.cpp:26: 'new
之前的解析错误 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;
}

【问题讨论】:

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


    【解决方案1】:

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

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

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

    而你的整个班级可能会因为unique_ptr&lt;Node&gt;s 而变得更好。

    【讨论】:

      【解决方案2】:

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

      node *new = new node;
      

      不合法

      【讨论】:

        【解决方案3】:

        newreserved word,不能用作变量名。

        【讨论】:

          猜你喜欢
          • 2022-11-15
          • 2016-02-04
          • 2020-02-28
          • 2013-11-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-21
          • 1970-01-01
          相关资源
          最近更新 更多