주어진 BST , 작업은 여기에 새 노드를 삽입하는 것입니다 BST .
예:

이진 검색 트리에 삽입
이진 검색 트리에 값을 삽입하는 방법:
이진 검색 트리의 속성을 유지하여 항상 리프에 새 키가 삽입됩니다. 리프 노드에 도달할 때까지 루트에서 키 검색을 시작합니다. 리프 노드가 발견되면 새 노드가 리프 노드의 하위로 추가됩니다. 이진 검색 트리에 노드를 삽입하려고 시도하는 동안 아래 단계를 따릅니다.
- 삽입할 값을 확인합니다(예: 엑스 )를 현재 노드의 값(예: 발 ) 현재 위치:
- 만약에 엑스 보다 작다 발 왼쪽 하위 트리로 이동합니다.
- 그렇지 않으면 오른쪽 하위 트리로 이동합니다.
- 리프 노드에 도달하면 삽입 엑스 사이의 관계에 따라 오른쪽이나 왼쪽으로 엑스 그리고 리프 노드의 값.
더 나은 이해를 위해 아래 그림을 따르십시오.
삽화:
BST에 삽입
BST에 삽입
BST에 삽입
BST에 삽입
BST에 삽입
재귀를 사용하여 이진 검색 트리에 삽입:
아래는 재귀를 이용한 삽입 연산의 구현입니다.
C++14
안키타 로칸데 나이
// C++ program to demonstrate insertion> // in a BST recursively> #include> using> namespace> std;> class> BST {> >int> data;> >BST *left, *right;> public>:> >// Default constructor.> >BST();> >// Parameterized constructor.> >BST(>int>);> >// Insert function.> >BST* Insert(BST*,>int>);> >// Inorder traversal.> >void> Inorder(BST*);> };> // Default Constructor definition.> BST::BST()> >: data(0)> >, left(NULL)> >, right(NULL)> {> }> // Parameterized Constructor definition.> BST::BST(>int> value)> {> >data = value;> >left = right = NULL;> }> // Insert function definition.> BST* BST::Insert(BST* root,>int> value)> {> >if> (!root) {> >// Insert the first node, if root is NULL.> >return> new> BST(value);> >}> >// Insert data.> >if> (value>루트->데이터) {> >// Insert right node data, if the 'value'> >// to be inserted is greater than 'root' node data.> >// Process right nodes.> >root->right = 삽입(루트->오른쪽, 값);> >}> >else> if> (value data) {> >// Insert left node data, if the 'value'> >// to be inserted is smaller than 'root' node data.> >// Process left nodes.> >root->왼쪽 = 삽입(루트->왼쪽, 값);> >}> >// Return 'root' node, after insertion.> >return> root;> }> // Inorder traversal function.> // This gives data in sorted order.> void> BST::Inorder(BST* root)> {> >if> (!root) {> >return>;> >}> >Inorder(root->왼쪽);> >cout ' '; Inorder(root->오른쪽); } // 드라이버 코드 int main() { BST b, *root = NULL; 루트 = b.Insert(루트, 50); b.삽입(루트, 30); b.삽입(루트, 20); b.삽입(루트, 40); b.삽입(루트, 70); b.삽입(루트, 60); b.삽입(루트, 80); b.순서(루트); 0을 반환합니다. }> |
>
>
씨
// C program to demonstrate insert> // operation in binary> // search tree.> #include> #include> struct> node {> >int> key;> >struct> node *left, *right;> };> // A utility function to create a new BST node> struct> node* newNode(>int> item)> {> >struct> node* temp> >= (>struct> node*)>malloc>(>sizeof>(>struct> node));> >temp->키 = 항목;> >temp->왼쪽 = 임시->오른쪽 = NULL;> >return> temp;> }> // A utility function to do inorder traversal of BST> void> inorder(>struct> node* root)> {> >if> (root != NULL) {> >inorder(root->왼쪽);> >printf>(>'%d '>, root->키);> >inorder(root->오른쪽);> >}> }> // A utility function to insert> // a new node with given key in BST> struct> node* insert(>struct> node* node,>int> key)> {> >// If the tree is empty, return a new node> >if> (node == NULL)> >return> newNode(key);> >// Otherwise, recur down the tree> >if> (key key)> >node->왼쪽 = 삽입(노드->왼쪽, 키);> >else> if> (key>노드->키)> >node->right = insert(노드->오른쪽, 키);> >// Return the (unchanged) node pointer> >return> node;> }> // Driver Code> int> main()> {> >/* Let us create following BST> >50> >/> >30 70> >/ /> >20 40 60 80 */> >struct> node* root = NULL;> >root = insert(root, 50);> >insert(root, 30);> >insert(root, 20);> >insert(root, 40);> >insert(root, 70);> >insert(root, 60);> >insert(root, 80);> >// Print inorder traversal of the BST> >inorder(root);> >return> 0;> }> |
>
>
자바
f영화
// Java program to demonstrate> // insert operation in binary> // search tree> import> java.io.*;> public> class> BinarySearchTree {> >// Class containing left> >// and right child of current node> >// and key value> >class> Node {> >int> key;> >Node left, right;> >public> Node(>int> item)> >{> >key = item;> >left = right =>null>;> >}> >}> >// Root of BST> >Node root;> >// Constructor> >BinarySearchTree() { root =>null>; }> >BinarySearchTree(>int> value) { root =>new> Node(value); }> >// This method mainly calls insertRec()> >void> insert(>int> key) { root = insertRec(root, key); }> >// A recursive function to> >// insert a new key in BST> >Node insertRec(Node root,>int> key)> >{> >// If the tree is empty,> >// return a new node> >if> (root ==>null>) {> >root =>new> Node(key);> >return> root;> >}> >// Otherwise, recur down the tree> >else> if> (key root.left = insertRec(root.left, key); else if (key>root.key) root.right = insertRec(root.right, key); // (변경되지 않은) 노드 포인터를 반환합니다. return root; } // 이 메서드는 주로 InorderRec()를 호출합니다. void inorder() { inorderRec(root); } // BST의 중위 순회를 // 수행하는 유틸리티 함수 void inorderRec(Node root) { if (root != null) { inorderRec(root.left); System.out.print(root.key + ' '); inorderRec(root.right); } } // 드라이버 코드 public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* 다음 BST를 생성해 보겠습니다. 50 / 30 70 / / 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); // BST tree.inorder()의 중순 순회를 인쇄합니다. } } // 이 코드는 Ankur Narain Verma가 제공한 것입니다.> |
>
>
파이썬3
# Python program to demonstrate> # insert operation in binary search tree> # A utility class that represents> # an individual node in a BST> class> Node:> >def> __init__(>self>, key):> >self>.left>=> None> >self>.right>=> None> >self>.val>=> key> # A utility function to insert> # a new node with the given key> def> insert(root, key):> >if> root>is> None>:> >return> Node(key)> >else>:> >if> root.val>=>=> key:> >return> root> >elif> root.val root.right = insert(root.right, key) else: root.left = insert(root.left, key) return root # A utility function to do inorder tree traversal def inorder(root): if root: inorder(root.left) print(root.val, end=' ') inorder(root.right) # Driver program to test the above functions if __name__ == '__main__': # Let us create the following BST # 50 # / # 30 70 # / / # 20 40 60 80 r = Node(50) r = insert(r, 30) r = insert(r, 20) r = insert(r, 40) r = insert(r, 70) r = insert(r, 60) r = insert(r, 80) # Print inorder traversal of the BST inorder(r)> |
>
>
씨#
// C# program to demonstrate> // insert operation in binary> // search tree> using> System;> class> BinarySearchTree {> >// Class containing left and> >// right child of current node> >// and key value> >public> class> Node {> >public> int> key;> >public> Node left, right;> >public> Node(>int> item)> >{> >key = item;> >left = right =>null>;> >}> >}> >// Root of BST> >Node root;> >// Constructor> >BinarySearchTree() { root =>null>; }> >BinarySearchTree(>int> value) { root =>new> Node(value); }> >// This method mainly calls insertRec()> >void> insert(>int> key) { root = insertRec(root, key); }> >// A recursive function to insert> >// a new key in BST> >Node insertRec(Node root,>int> key)> >{> >// If the tree is empty,> >// return a new node> >if> (root ==>null>) {> >root =>new> Node(key);> >return> root;> >}> >// Otherwise, recur down the tree> >if> (key root.left = insertRec(root.left, key); else if (key>root.key) root.right = insertRec(root.right, key); // (변경되지 않은) 노드 포인터를 반환합니다. return root; } // 이 메서드는 주로 InorderRec()를 호출합니다. void inorder() { inorderRec(root); } // BST의 중위 순회를 // 수행하는 유틸리티 함수 void inorderRec(Node root) { if (root != null) { inorderRec(root.left); Console.Write(root.key + ' '); inorderRec(root.right); } } // 드라이버 코드 public static void Main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* 다음 BST를 생성해 보겠습니다. 50 / 30 70 / / 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); // BST tree.inorder()의 중순 순회를 인쇄합니다. } } // 이 코드는 aashish1995가 제공한 것입니다.> |
>
>
자바스크립트
> // javascript program to demonstrate> // insert operation in binary> // search tree> >/*> >* Class containing left and right child of current node and key value> >*/> >class Node {> > constructor(item) {> >this>.key = item;> >this>.left =>this>.right =>null>;> >}> >}> >// Root of BST> >var> root =>null>;> >// This method mainly calls insertRec()> >function> insert(key) {> >root = insertRec(root, key);> >}> >// A recursive function to insert a new key in BST> >function> insertRec(root, key) {> >// If the tree is empty, return a new node> >if> (root ==>null>) {> >root =>new> Node(key);> >return> root;> >}> >// Otherwise, recur down the tree> >if> (key root.left = insertRec(root.left, key); else if (key>root.key) root.right = insertRec(root.right, key); // (변경되지 않은) 노드 포인터를 반환합니다. return root; } // 이 메서드는 주로 InorderRec() 함수를 호출합니다. inorder() { inorderRec(root); } // BST의 중위 순회를 수행하는 // 유틸리티 함수 function inorderRec(root) { if (root != null) { inorderRec(root.left); document.write(root.key+' '); inorderRec(root.right); } } // 드라이버 코드 /* BST 50 / 30 70 / / 20 40 60 80 */ insert(50); 삽입(30); 삽입(20); 삽입(40); 삽입(70); 삽입(60); 삽입(80); // BST의 중순 순회를 인쇄합니다. inorder(); // 이 코드는 Rajput-Ji가 제공한 것입니다.> |
>
>산출
20 30 40 50 60 70 80>
시간 복잡도:
- 삽입 작업의 최악의 시간 복잡도는 다음과 같습니다. 오) 어디 시간 이진 검색 트리의 높이입니다.
- 최악의 경우 루트에서 가장 깊은 리프 노드까지 이동해야 할 수도 있습니다. 기울어진 나무의 높이는 N 삽입 작업의 시간 복잡도가 높아질 수 있습니다. 에).
보조 공간: 보조 이진 검색 트리에 삽입할 때의 공간 복잡도는 다음과 같습니다. 오(1)
반복적 접근 방식을 사용하여 이진 검색 트리에 삽입:
재귀를 사용하는 대신 다음을 사용하여 삽입 작업을 반복적으로 구현할 수도 있습니다. while 루프 . 다음은 while 루프를 사용한 구현입니다.
q1 q2 q3 q4
C++
// C++ Code to insert node and to print inorder traversal> // using iteration> #include> using> namespace> std;> // BST Node> class> Node {> public>:> >int> val;> >Node* left;> >Node* right;> >Node(>int> val)> >: val(val)> >, left(NULL)> >, right(NULL)> >{> >}> };> // Utility function to insert node in BST> void> insert(Node*& root,>int> key)> {> >Node* node =>new> Node(key);> >if> (!root) {> >root = node;> >return>;> >}> >Node* prev = NULL;> >Node* temp = root;> >while> (temp) {> >if> (temp->값> 키) {> >prev = temp;> >temp = temp->왼쪽;> >}> >else> if> (temp->값 이전 = 온도; 온도 = 온도->오른쪽; } } if (prev->val> key) prev->left = node; else prev->right = 노드; } // 중위 순회를 인쇄하는 유틸리티 함수 void inorder(Node* root) { Node* temp = root; 스택 st; while (temp != NULL || !st.empty()) { if (temp != NULL) { st.push(temp); 온도 = 온도->왼쪽; } else { 임시 = st.top(); st.pop(); cout ' '; 온도 = 온도->오른쪽; } } } // 드라이버 코드 int main() { Node* root = NULL; insert(루트, 30); insert(루트, 50); insert(루트, 15); insert(루트, 20); insert(루트, 10); insert(루트, 40); insert(루트, 60); // 중위 순회를 인쇄하는 함수 호출 inorder(root); 0을 반환합니다. }> |
>
>
자바
// Java code to implement the insertion> // in binary search tree> import> java.io.*;> import> java.util.*;> class> GFG {> >// Driver code> >public> static> void> main(String[] args)> >{> >BST tree =>new> BST();> >tree.insert(>30>);> >tree.insert(>50>);> >tree.insert(>15>);> >tree.insert(>20>);> >tree.insert(>10>);> >tree.insert(>40>);> >tree.insert(>60>);> >tree.inorder();> >}> }> class> Node {> >Node left;> >int> val;> >Node right;> >Node(>int> val) {>this>.val = val; }> }> class> BST {> >Node root;> >// Function to insert a key> >public> void> insert(>int> key)> >{> >Node node =>new> Node(key);> >if> (root ==>null>) {> >root = node;> >return>;> >}> >Node prev =>null>;> >Node temp = root;> >while> (temp !=>null>) {> >if> (temp.val>키) {> >prev = temp;> >temp = temp.left;> >}> >else> if> (temp.val prev = temp; temp = temp.right; } } if (prev.val>키) prev.left = 노드; 그렇지 않으면 prev.right = 노드; } // 중위값을 출력하는 함수 public void inorder() { Node temp = root; 스택 스택 = new Stack(); while (temp != null || !stack.isEmpty()) { if (temp != null) { stack.add(temp); 온도 = temp.left; } else { 임시 = stack.pop(); System.out.print(temp.val + ' '); 온도 = temp.right; } } } }> |
>
>
파이썬3
# Python 3 code to implement the insertion> # operation iteratively> class> GFG:> >@staticmethod> >def> main(args):> >tree>=> BST()> >tree.insert(>30>)> >tree.insert(>50>)> >tree.insert(>15>)> >tree.insert(>20>)> >tree.insert(>10>)> >tree.insert(>40>)> >tree.insert(>60>)> >tree.inorder()> class> Node:> >left>=> None> >val>=> 0> >right>=> None> >def> __init__(>self>, val):> >self>.val>=> val> class> BST:> >root>=> None> ># Function to insert a key in the BST> >def> insert(>self>, key):> >node>=> Node(key)> >if> (>self>.root>=>=> None>):> >self>.root>=> node> >return> >prev>=> None> >temp>=> self>.root> >while> (temp !>=> None>):> >if> (temp.val>키):> >prev>=> temp> >temp>=> temp.left> >elif>(temp.val prev = temp temp = temp.right if (prev.val>key): prev.left = node else: prev.right = node # BST의 중위순회를 인쇄하는 함수 def inorder(self): temp = self.root stack = [] while (temp != None or not (len( stack) == 0)): if (temp != None): stack.append(temp) temp = temp.left else: temp = stack.pop() print(str(temp.val) + ' ', end='') temp = temp.right if __name__ == '__main__': GFG.main([]) # 이 코드는 rastogik346에 의해 기여되었습니다.> |
>
>
씨#
러드야드 키플링의 말을 바꿔서 말해보세요
// Function to implement the insertion> // operation iteratively> using> System;> using> System.Collections.Generic;> public> class> GFG {> >// Driver code> >public> static> void> Main(String[] args)> >{> >BST tree =>new> BST();> >tree.insert(30);> >tree.insert(50);> >tree.insert(15);> >tree.insert(20);> >tree.insert(10);> >tree.insert(40);> >tree.insert(60);> >// Function call to print the inorder traversal> >tree.inorder();> >}> }> public> class> Node {> >public> Node left;> >public> int> val;> >public> Node right;> >public> Node(>int> val) {>this>.val = val; }> }> public> class> BST {> >public> Node root;> >// Function to insert a new key in the BST> >public> void> insert(>int> key)> >{> >Node node =>new> Node(key);> >if> (root ==>null>) {> >root = node;> >return>;> >}> >Node prev =>null>;> >Node temp = root;> >while> (temp !=>null>) {> >if> (temp.val>키) {> >prev = temp;> >temp = temp.left;> >}> >else> if> (temp.val prev = temp; temp = temp.right; } } if (prev.val>키) prev.left = 노드; 그렇지 않으면 prev.right = 노드; } // BST의 중위 순회를 인쇄하는 함수 public void inorder() { Node temp = root; 스택 스택 = new Stack(); while (temp != null || stack.Count != 0) { if (temp != null) { stack.Push(temp); 온도 = temp.left; } else { 임시 = stack.Pop(); Console.Write(temp.val + ' '); 온도 = temp.right; } } } } // 이 코드는 Rajput-Ji가 제공한 것입니다.> |
>
>
자바스크립트
// JavaScript code to implement the insertion> // in binary search tree> class Node {> >constructor(val) {> >this>.left =>null>;> >this>.val = val;> >this>.right =>null>;> >}> }> class BST {> >constructor() {> >this>.root =>null>;> >}> >// Function to insert a key> >insert(key) {> >let node =>new> Node(key);> >if> (>this>.root ==>null>) {> >this>.root = node;> >return>;> >}> >let prev =>null>;> >let temp =>this>.root;> >while> (temp !=>null>) {> >if> (temp.val>키) {> >prev = temp;> >temp = temp.left;> >}>else> if> (temp.val prev = temp; temp = temp.right; } } if (prev.val>키) prev.left = 노드; 그렇지 않으면 prev.right = 노드; } // 중위값을 인쇄하는 함수 inorder() { let temp = this.root; 스택 = []; while (temp != null || stack.length> 0) { if (temp != null) { stack.push(temp); 온도 = temp.left; } else { 임시 = stack.pop(); console.log(temp.val + ' '); 온도 = temp.right; } } } } let tree = new BST(); tree.insert(30); tree.insert(50); tree.insert(15); tree.insert(20); tree.insert(10); tree.insert(40); tree.insert(60); tree.inorder(); // 이 코드는 devendrasolunke가 제공한 것입니다.> |
>
>산출
10 15 20 30 40 50 60>
그만큼 시간 복잡도 ~의 중위순회 ~이다 에) , 각 노드가 한 번씩 방문되기 때문입니다.
그만큼 보조 공간 ~이다 에) , 재귀를 위해 노드를 저장하기 위해 스택을 사용하기 때문입니다.
관련된 링크들:
- 이진 검색 트리 검색 작업
- 이진 검색 트리 삭제 작업




