2011-11-29 58 views
0

我在我的代码中收到解析错误。我可能错过了一些愚蠢的东西......但在盯着它看后,我无法弄清楚什么是错的。二进制搜索树无法正常工作? (解析错误)

BinaryTree.cpp:26:错误在第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

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

在任何情况下,你的构造会过得更好为:

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

而且你的类作为一个整体很可能​​会与unique_ptr<Node>好多了断。

3

新是在C关键字++,你不能说出与字变量,所以

node *new = new node; 

是非法