简体   繁体   中英

Binary search tree insertion

Need help to figure out why the following code for basic Binary Search Tree insertion is not working. Since I have been working on C# for sometime now, I'm afraid I forgot some of my C++. Also, any suggestions to improve coding style would be very helpful. (I know I'm not freeing memory as of now)

struct Node
    {
        int data;
        Node* lChild;
        Node* rChild;

        Node(int dataNew)
        {
            data = dataNew;
            lChild = NULL;
            rChild = NULL;
        }
    };

    class BST
    {
    private:
        Node* root; 

        void Insert(int newData, Node* &cRoot)  //is this correct?
        {
            if(cRoot == NULL)
            {
                cRoot = new Node(newData);
                return;
            }

            if(newData < cRoot->data)
                Insert(cRoot->data, cRoot->lChild);
            else
                Insert(cRoot->data, cRoot->rChild);
        }

        void PrintInorder(Node* cRoot)
        {
            if(cRoot != NULL)
            {
                PrintInorder(cRoot->lChild);
                cout<< cRoot->data <<" ";;
                PrintInorder(cRoot->rChild);
            }
        }

    public:
        BST()
        {
            root = NULL;
        }

        void AddItem(int newData)
        {
            Insert(newData, root);
        }

        void PrintTree()
        {
            PrintInorder(root);
        }
    };

    int main()
    {
        BST *myBST = new BST();
        myBST->AddItem(5);
        myBST->AddItem(7);
        myBST->AddItem(1);
        myBST->AddItem(10);
        myBST->PrintTree();
    }

It appears to me that

Insert(cRoot->data, cRoot->lChild);

should instead be

Insert(newData, cRoot->lChild);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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