之前我的思路是, 先用一个指针找到合适的位置, 再通过指针把值传进去……然后就陷入多重指针的深渊里了。
后来我的解决方法是递归:
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; } } } };
时间: 2024-11-06 19:53:45