하나의 이진 검색 트리가 있다고 가정하고 이제 이 BST의 두 요소가 바뀌었다고 가정하고 이 이진 검색 트리를 복구해야 합니다.
따라서 주어진 트리가 아래와 같으면(첫 번째 트리) 복구된 트리는 (두 번째 트리) −
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
노드에 대한 일부 이전, 첫 번째, 두 번째 참조 정의
-
findProblem()이라는 하나의 메서드를 정의하면 노드가 필요합니다.
-
노드가 null이면 반환
-
findProblem(노드 왼쪽)
호출 -
prev가 null이 아니고 prev의 값> 노드의 값인 경우
-
first가 null이면 first =prev
-
두 번째 :=노드
-
-
이전 :=노드
-
findProblem(노드 오른쪽)
호출 -
주요 방법에서 다음을 수행하십시오 -
-
prev, 첫 번째 및 두 번째를 null로 초기화하고 findProblem(root)를 호출하고 첫 번째 및 두 번째 노드의 값을 교환합니다.
예시(C++)
더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −
#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 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* prev; TreeNode* first; TreeNode* second; void swapValue(TreeNode* first, TreeNode* second){ int x = first->val; first->val = second -> val; second->val = x; } void findProblem(TreeNode* node){ if(!node || node->val == 0)return; findProblem(node->left); if((prev!=NULL && prev->val != 0) && prev->val> node->val){ if(!first){ first = prev; } second = node; } prev = node; findProblem(node->right); } void recoverTree(TreeNode* root) { prev = first = second = NULL; findProblem(root); swapValue(first, second); } }; main(){ vector<int> v = {1,3,NULL,NULL,2}; TreeNode *root = make_tree(v); Solution ob; ob.recoverTree(root); tree_level_trav(root); }
입력
{1,3,NULL,NULL,2}
출력
[3, 1, null, null, 2, ]