困扰这个二叉树代码(在c ++中)?

时间:2015-06-21 15:30:27

标签: c++ binary-tree

这是我编写的用于插入和遍历二叉树的代码。不过我现在搞砸了。你可以帮我纠正一下吗?插入代码中的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();
}

2 个答案:

答案 0 :(得分:2)

您正在构造函数中为根分配NULL:

root = NULL;

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

答案 1 :(得分:1)

请注意,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);
    }

  }
相关问题