简体   繁体   English

二进制搜索树插入

[英]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++. 由于我一直在研究C#,我恐怕忘记了一些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);

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

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