zoukankan      html  css  js  c++  java
  • 二叉树链表的实现: Insert()

    之前我的思路是, 先用一个指针找到合适的位置, 再通过指针把值传进去……然后就陷入多重指针的深渊里了。

    后来我的解决方法是递归:

    class BinarySearchTree
    {
    private:
        // do something...
    
        PTreeNode MakeNewNode (const int32_t& value)
        {
            auto newNode       = make_shared<TreeNode> ();
            newNode->key       = value;
            return move(newNode);
        }
    
        void InsertIter (PTreeNode& node, const int32_t& value)
        {
            if (node == nullptr) {
                node = MakeNewNode (value);
            }
            else {
                if (node->key < value) {
                    InsertIter (node->rightNode, value);
                }
                else {
                    InsertIter (node->leftNode, value);
                }
            }
        }
    public:
        void Insert (const int32_t& value)
        {
            InsertIter (root, value);
        }
    
        // other functions...
    };

    后来在知乎看到了 @坡下碎石 的解答, 深受启发, 有了迭代版本:

    struct TreeNode
    {
    
        int32_t              key = 0;
        PTreeNode            leftNode = nullptr;
        PTreeNode            rightNode = nullptr;
    
        PTreeNode& MoveToNextNode(const int32_t& value)
        {
            return key < value ? rightNode : leftNode;
        }
    };
    
    class BinarySearchTree
    {
    private:
        PTreeNode   root;
    
        PTreeNode MakeNewNode(const int32_t& value)
        {
            auto newNode = std::make_shared<TreeNode>();
            newNode->key = value;
            return newNode;
        }
    
    public:
        void Insert(const int32_t& value)
        {
            if (root == nullptr)
            {
                root = MakeNewNode(value);
            }
            else
            {
                PTreeNode current = root;
                while (true)
                {
                    PTreeNode& p = current->MoveToNextNode(value);
                    if (p == nullptr)
                    {
                        p = MakeNewNode(value);
                        break;
                    }
                    current = p;
                }
            }
        }
    };
  • 相关阅读:
    本月周六周日LIST集合
    c#动态调用WEBSERVICE接口
    c#调用
    web上传下载文件
    MVC 的知识
    MongoDB 无法创建抽象类的问题,
    并行活动
    C# 字符串计算表达式
    c# 将字符串转换为逻辑表达式(字符串转换布尔)
    C# 中间语言、CLR、CTS、CLS
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4303170.html
Copyright © 2011-2022 走看看