簡體   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