首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >二叉树插入

二叉树插入
EN

Stack Overflow用户
提问于 2011-09-24 13:32:38
回答 1查看 1.1K关注 0票数 0

我需要帮助找出为什么下面的基本二进制搜索树插入代码不起作用。因为我已经在C#上工作了一段时间了,我恐怕我忘了我的一些C++。此外,任何改进编码风格的建议都会非常有帮助。(我知道我现在还没有释放内存)

代码语言:javascript
运行
复制
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();
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-09-24 13:45:24

在我看来

代码语言:javascript
运行
复制
Insert(cRoot->data, cRoot->lChild);

应该改为

代码语言:javascript
运行
复制
Insert(newData, cRoot->lChild);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7537262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档