이진 탐색 트리가 있다고 가정하고 동일한 노드 값을 가진 균형 이진 탐색 트리를 찾아야 합니다. 이진 탐색 트리는 모든 노드의 두 하위 트리의 깊이가 1 이상 차이가 나지 않는 경우에만 균형이 잡힌다고 합니다. 결과가 둘 이상인 경우 그 중 하나를 반환합니다. 트리가 다음과 같다면 -

이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
inorder() 메서드를 정의하면 순서 순회 시퀀스가 배열에 저장됩니다.
-
구성 메서드()를 정의하면 낮고 높음이 소요됩니다. −
-
낮음> 높으면 null 반환
-
중간 :=낮음 + (높음 - 낮음) / 2
-
root :=값이 arr[mid]
인 새 노드 -
루트 왼쪽 :=구성(낮음, 중간 – 1) 및 루트 오른쪽 :=구성(중간 + 1, 높음)
-
루트 반환
-
메인 메서드에서 inorder 메서드를 호출하고 생성자(0, size of arr - 1)
를 반환합니다.
예시(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:
vector <int> arr;
void inorder(TreeNode* node){
if(!node || node->val == 0) return;
inorder(node->left);
arr.push_back(node->val);
inorder(node->right);
}
TreeNode* construct(int low, int high){
if(low > high) return NULL;
int mid = low + (high - low) / 2;
TreeNode* root = new TreeNode(arr[mid]);
root->left = construct(low, mid - 1);
root->right = construct(mid + 1, high);
return root;
}
TreeNode* balanceBST(TreeNode* root) {
inorder(root);
return construct(0, (int)arr.size() - 1);
}
};
main(){
vector<int> v = {1,NULL,2,NULL,NULL,NULL,3,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4};
TreeNode *root = make_tree(v);
Solution ob;
tree_level_trav(ob.balanceBST(root));
} 입력
[1,NULL,2,NULL,NULL,NULL,3,NULL,NULL,NULL,NULL,NULL,NULL,NULL,4]
출력
[2, 1, 3, 4, ]