Binary Search Tree Insertion in C++ - Balancing Issue with Duplicate Values
Hey everyone, I'm running into an issue that's driving me crazy. I've looked through the documentation and I'm still confused about I'm stuck on something that should probably be simple... Quick question that's been bugging me - I'm facing an issue with my implementation of a Binary Search Tree (BST) in C++. When I try to insert duplicate values, the tree becomes unbalanced, leading to inefficient searches. I am using a simple node structure and an insert function that places duplicates to the right. However, this doesn't seem to maintain a balanced tree structure. Here's a snippet of my code: ```cpp struct TreeNode { int value; TreeNode* left; TreeNode* right; TreeNode(int val) : value(val), left(nullptr), right(nullptr) {} }; class BinarySearchTree { private: TreeNode* root; void insert(TreeNode*& node, int val) { if (!node) { node = new TreeNode(val); } else if (val < node->value) { insert(node->left, val); } else { insert(node->right, val); } } public: BinarySearchTree() : root(nullptr) {} void insert(int val) { insert(root, val); } }; ``` When I insert values like `5, 3, 8, 5, 2, 7`, I expect the tree to maintain some balance, but it skews heavily to the right because of the duplicates. This leads to search times that are closer to O(n) instead of O(log n). I've considered implementing a balancing mechanism, such as an AVL tree, but I'm unsure how to approach that without completely rewriting my insertion logic. Currently, I'm just checking for duplicates but not handling them properly. Could anyone suggest a way to manage duplicates in my BST while keeping the tree balanced, or recommend whether I should switch to a self-balancing tree structure? Thanks in advance! My development environment is macOS. My development environment is Windows 10. Thanks for taking the time to read this! Am I missing something obvious?