Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 BST에서 노드 삭제

<시간/>

이진 검색 트리가 있다고 가정합니다. 하나의 키 k를 가져와서 BST에서 주어진 키 k를 삭제하고 업데이트된 BST를 반환해야 합니다. 트리가 다음과 같다면 -

C++의 BST에서 노드 삭제


키 k =3이면 출력 트리는 -

가 됩니다.

C++의 BST에서 노드 삭제


이 문제를 해결하기 위해 다음 단계를 따릅니다. −

  • 루트 노드를 삭제하기 위해 deleteRoot()라는 메서드를 정의하면 다음과 같이 작동합니다.

  • 루트가 null이면 null을 반환합니다.

  • 루트에 오른쪽 하위 트리가 없으면 루트의 왼쪽을 반환

  • x :=루트의 순서 없는 계승자

  • x의 왼쪽을 왼쪽으로 설정 :=루트의 왼쪽

  • 루트의 오른쪽 반환

  • 삭제 방법은 다음과 같습니다.

  • root가 null이거나 root의 값이 key이면 deleteRoot(root)

    를 반환합니다.
  • curr :=루트

  • 하나의 무한 루프를 만들고 다음을 실행하십시오.

    • x :=현재 노드의 값

      • curr의 왼쪽 =null 또는 curr의 왼쪽 값 =key인 경우

        • left of curr :=deleteRoot(left of curr) 루프에서 나옵니다.

      • curr :=curr의 왼쪽

    • 그렇지 않으면

      • curr의 오른쪽 =null 또는 curr의 오른쪽 값 =키인 경우

        • right of curr :=deleteRoot(right of curr) 및 루프에서 나옵니다.

      • curr :=curr의 오른쪽

  • 루트 반환

이해를 돕기 위해 다음 구현을 살펴보겠습니다. −

예시

#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   public:
   int val;
   TreeNode *left, *right;
   TreeNode(int data){
      val = data;
      left = NULL;
      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 == NULL || curr->val == 0){
            cout << "null" << ", ";
         } else {
            cout << curr->val << ", ";
         }
      }
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   TreeNode* deleteNode(TreeNode* root, int key) {
      if(root == NULL || root->val == key) return deleteRoot(root);
         TreeNode* curr = root;
      while(1) {
         int x = curr->val;
         if(key < x){
            if(curr->left == NULL || curr->left->val == key){
               curr->left = deleteRoot(curr->left);
               break;
            }
            curr = curr->left;
         } else {
            if(curr->right == NULL || curr->right->val == key){
               curr->right = deleteRoot(curr->right);
               break;
            }
            curr = curr->right;
         }
      }
      return root;
   }
   TreeNode* deleteRoot(TreeNode* root){
         if(!root || root->val == 0)return NULL;
            if(root->right == NULL) return root->left;
         TreeNode* x = root->right;
         while(x->left)x = x->left;
         x->left = root->left;
         return root->right;
      }
   };
main(){
   vector<int> v = {5,3,6,2,4,NULL,7};
   TreeNode *root = make_tree(v);
   Solution ob;
   tree_level_trav(ob.deleteNode(root, 3));
}

입력

[5,3,6,2,4,null,7]
3

출력

[5, 4, 6, 2, null, 7, ]