二叉树只添加到根

时间:2015-11-15 23:13:16

标签: c++ tree binary-tree

我正在用C ++编写一个简单的二进制树程序,现在它只存储在根节点输入的最新值,例如。如果我在树中输入10然后在树中输入9,那么9只会覆盖10作为根节点,因此树只存储值9。

我已经在线查看了多个C ++二进制树解决方案,并尝试了实现它们的版本,但仍然没有成功。

这是我树中单个节点的结构

struct TreeNode{

    int value;
    TreeNode *left;
    TreeNode *right;

    TreeNode(int value){

        this -> value = value;
        left = NULL;
        right = NULL;

    }
};

到目前为止我的二叉树类

class IntTree{

private :

    TreeNode *root;

public :

    IntTree();
    TreeNode* getRoot();
    void insertValue(TreeNode *root, int intValue);
    TreeNode* searchTree(TreeNode *root, int intValue);
    void inOrder(TreeNode *root);
    void deleteValue(int intValue);
    void deleteTree(TreeNode *root);

};

插入方法

void IntTree::insertValue(TreeNode *root, int intValue){


if(root == NULL){

    root = new TreeNode(intValue);

}

else if(intValue == root->value){

    cout << "Value already exists in the tree" << endl;

}

else if(intValue < root->value){

    insertValue(root->left, intValue);

}

else{

    insertValue(root->right, intValue);

}   
}

然后在这样的菜单中调用此方法

cout << "Enter Value to Insert : " << endl;
input = readInt();
theTree.insertValue(theTree.getRoot(), input);

逻辑对我来说似乎都很好,除了我尝试不使用构造函数并且只是简单地设置变量,有两个函数用于插入只有int参数的函数,所以我不会这样做以后必须使用getRoot()以及我忘记的其他一百万个

2 个答案:

答案 0 :(得分:1)

答案很简单,您正在修改的指针只是一个副本,因此在函数结束时丢弃该副本并且您丢失了内存。你需要在指针上引用一个实际修改它的指针(没有别的东西可以修改):

void insertValue(TreeNode *& root, int intValue)

答案 1 :(得分:0)

这应该有效:

新的insertvalue函数调用将如下所示

void insertValue(TreeNode **root, int intValue)
{
  if(*root == NULL)
  {
      *root = newNode(intValue);
  }
  else if(intValue == (*root)->value)
  {
     cout << "Value already exists in the tree" << endl;
  }
  else if(intValue < (*root)->value)
  {
    insertValue(&(*(root))->left, intValue);
  }
  else
  {
    insertValue(&(*(root))->right, intValue);
  }   
}
int main()
{
    //initial code
    insertvalue(&root,value) //root is a single pointer variable.
    //code for printing the tree
}

实现相同的方法有很多不太复杂的方法。我刚刚修改了你的代码。