此二进制树代码出现问题(在c++中)

Troubled with this binary tree code (in c++)?

本文关键字:c++ 问题 二进制 代码      更新时间:2023-10-16

这是我为二进制树的插入和有序遍历而编写的代码。不过我现在有点乱了。你能帮我纠正一下吗?插入代码中的while循环没有任何内容。感谢您的帮助。

#include<iostream>
#include<string>
using namespace std;
class binarynode
{public:
string data;
binarynode *left;
binarynode *right;  
};
class tree
{
binarynode *root;
public:
    tree()
    {
        root=new binarynode;
        root=NULL;
    }
    binarynode* createnode(string value)
    {
        binarynode * temp;
        temp=new binarynode;
        temp->data=value;   
        temp->left=NULL;
        temp->right=NULL;
        return temp;
    }
    void insert(string value)
    {//cout<<"entered 1"<<endl;
        binarynode * nroot;
        nroot=root;
        while(nroot!=NULL)
        {//cout<<"here 2"<<endl;
        if(value> nroot->data )
        {
        //  cout<<"here 3"<<endl;
            nroot=nroot->right;
        }
        else
        if(value<nroot->data)
        {//cout<<"here 4"<<endl;
            nroot=nroot->left;
        }
        }
        nroot=createnode(value);
    }
    void inorder()
    {
        binarynode *nroot;
        nroot=root;
        printinorder(nroot);
    }
    void printinorder(binarynode * nroot)
    {
    //cout<<"entered 5"<<endl;
        if(nroot->left==NULL&&nroot->right==NULL)
        {
            cout<<nroot->data<<" ";
        }
            printinorder(nroot->left);
    cout<<nroot->data<<" ";
    printinorder(nroot->right);
    }
};
int main()
{
    tree a;
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        string value;
        cin>>value;
        a.insert(value);
    }
    a.inorder();
}

您在构造函数中将NULL赋值给根:

root = NULL;

所以你的while循环永远不会被输入。

请注意,nroot=createnode(value);不会将节点追加到树中。你可以使用双指针。

编辑:根据yeldar 的要求

  void insert(const std::string& value) {
    binarynode **node = &root;
    while (*node) {
      if (value >= (*node)->data) {
        node=&(*node)->right;
      } else {
        node=&(*node)->left;
      }
    }
    *node=createnode(value);
  }

编辑:不使用双指针

  void insert(const std::string& value) {
    if (root == NULL) {
      root = createnode(value);
      return;
    }
    binarynode *node = root;
    binarynode *parent = NULL;
    while (node) {
      parent = node; // we should store the parent node                                                                                                        
      node = value >= parent->data ? parent->right : parent->left;
    }
    if (value >= parent->data) {
      parent->right = createnode(value);
    } else {
      parent->left = createnode(value);
    }
  }