繁体   English   中英

二叉树仅添加到根

[英]Binary Tree only adding to the the root

我正在用C ++写一个简单的Binary Tree程序,现在它只存储在根节点上输入的最新值,例如。 如果我在树中输入10,然后在树中输入9,则9会覆盖10作为根节点,因此树仅存储值9​​。

我在线上查看了多个C ++ Binary Tree解决方案,并尝试了其实现它们的版本,但仍然没有成功。

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

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()后来还有我忘记的一百万件事

答案很简单,您正在修改的指针只是一个副本,因此该副本在函数末尾被丢弃,并且您已经失去了内存。 您需要在指针上进行引用以实际对其进行修改(无需修改):

void insertValue(TreeNode *& root, int intValue)

这应该工作:

新的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
}

有许多不太复杂的方法可以实现相同的目的。 我刚刚修改了您的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM