바이너리 검색 트리가 있다고 가정합니다. 매개변수로 지정된 노드로 삽입 작업을 수행하는 메서드를 하나만 작성하면 됩니다. 수술 후에도 트리는 BST로 유지된다는 점을 염두에 두어야 합니다. 트리가 다음과 같다면 -

5를 삽입하면 트리는 -
가 됩니다.

이 문제를 해결하기 위해 다음 단계를 따릅니다. −
- 이 방법은 재귀적입니다. 이것을 insert()라고 하며 v 값을 취합니다.
- 루트가 null이면 주어진 값 v로 노드를 생성하고 루트로 만듭니다.
- 루트의 값이 v이면
- 루트의 왼쪽 :=insert(루트의 왼쪽, v)
- 루트의 else 오른쪽 :=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]