插入算法流程图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8044ad10ade65f0ca77b3e3b4ed26956.png)
创建二叉搜索树节点
TreeNode* CreateBnarySearchTreeNode(const TreeKey &value, TreeNode* Where=nullptr) {
TreeNode* newTreeNode = new TreeNode{ value, Where, Where };
return newTreeNode;
}
TreeNode* newTreeNode = CreateBnarySearchTreeNode(value);
判断根节点为空?
const bool isRootNodeEmpty = tree.Root;
if (!isRootNodeEmpty){
tree.Root = newTreeNode;
}
循环找到插入的结点
if(isRootNodeEmpty){
TreeNode* InsertNode= nullptr;
while (currentNode) {
InsertNode = currentNode;
if (currentNode->value< newTreeNode->value) {
currentNode = currentNode->LeftChild;
}else{
currentNode = currentNode->RightChild;
}
}
}
判断插入到孩子节点
const bool isLertInsert = InsertNode->value < newTreeNode->value;
if (isLertInsert){
InsertNode->LeftChild = newTreeNode;
}else{
InsertNode->RightChild = newTreeNode;
}
}
二叉搜索树节点个数增一
++tree.size;
插入算法分析
插入元素:1
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/74362a939ed84d62afd03c06f7db7070.png)
插入元素:9
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1db73ac247568e3241b25adfbb67435c.png)
插入元素:8
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3842e6a48d19a49ae7306986c0e40248.png)
插入元素:6
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ac749ae046dcbc52e66d0a67b80ec1da.png)
完全插入效果展示:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4ce59797bcf6412602eb2d4db06d5d9e.png)
插入算法-完整版
void BinarySearchTree_Insert(BinarySearchTree & tree, const TreeKey & value) {
TreeNode* newTreeNode = CreateBnarySearchTreeNode(value);
const bool isRootNodeEmpty = tree.Root;
if (!isRootNodeEmpty) {
tree.Root = newTreeNode;
}
TreeNode* currentNode = tree.Root;
if (isRootNodeEmpty) {
TreeNode* InsertNode = nullptr;
while (currentNode) {
InsertNode = currentNode;
if (newTreeNode->value < currentNode->value) {
currentNode = currentNode->LeftChild;
}
else {
currentNode = currentNode->RightChild;
}
}
const bool isLertInsert = newTreeNode->value < InsertNode->value;
if (isLertInsert) {
InsertNode->LeftChild = newTreeNode;
}
else {
InsertNode->RightChild = newTreeNode;
}
}
++tree.size;
}