插入 C++ 中的二叉搜索树
假设我们有一棵二叉搜索树。我们只写一个方法,它将执行以作为参数给定的节点的插入操作。我们必须记住,操作完成后,该树还将保持为 BST。因此,如果树如下所示 −

如果我们插入 5,那么树将变成 −

为了解决这个问题,我们将遵循以下步骤 −
- 此方法是递归的。这称为 insert(),它采用一个值 v。
- 如果根为 null,则使用给定的值 v 创建一个节点,并将其作为根
- 如果根的值 > v,则
- 根的左节点 := insert(根的左节点,v)
- 否则根的右节点 := insert(根的右节点,v)
- 返回根
示例 (C++)
让我们查看以下实现方式,以获得更好的理解 −
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
}
else{
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
}
else{
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
void tree_level_trav(TreeNode*root){
if (root == NULL) return;
cout << "[";
queue<TreeNode *> q;
TreeNode *curr;
q.push(root);
q.push(NULL);
while (q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL){
q.push(NULL);
}
else {
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
if(curr->val == 0 || curr == NULL){
cout << "null" << ", ";
}
else{
cout << curr->val << ", ";
}
}
}
cout << "]"<<endl;
}
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(!root)return new TreeNode(val);
if(root->val > val){
root->left = insertIntoBST(root->left, val);
}
else root->right = insertIntoBST(root->right, val);
return root;
}
};
main(){
Solution ob;
vector<int> v = {4,2,7,1,3};
TreeNode *root = make_tree(v);
tree_level_trav(ob.insertIntoBST(root, 5));
}输入
[4,2,7,1,3] 5
输出
[4,2,7,1,3,5]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP