트리를 균형있게 유지하면서 트리에 값을 삽입하여 배열을 반복적으로 통과하는 함수를 작성하려고합니다. 배열이 정렬되어 있고 크기를 알고 있다고 가정합니다. 내가해야 할 일은 배열 중간에서부터 시작하여 그 값을 루트에 삽입 한 다음 왼쪽 및 오른쪽 반의 가운데를 가져 와서 루트의 왼쪽 및 오른쪽 노드에 삽입하는 식으로 이해하는 것입니다. 배열이 채워질 때까지. 재귀가 가장 먼저 떠오르는 것이고 코딩 한 것은 의미가 있지만 의도 한대로 작동하지 않는 것 같습니다.배열 C++에서 균형 이진 검색 트리 초기화
문제점 처음 값과 마지막 값이 삽입되지 않고 각 잎의 왼쪽과 오른쪽에 NULL이 아닌 쓰레기 값이있는 노드가 있습니다.
간단한 (강사 제공)하는 노드의 구조 : 생성자
// ---------------------------------------------------------------------------
// Constructor (from sorted array)
//
template<class T>
BinarySearchTree<T>::BinarySearchTree(T *elements, int n_elements) {
int high = n_elements-1;
int low = 0;
root = new BTNode<T>;
BSTreeHelper(low, high, elements, BinaryTree<T>::root);
}
도우미 함수 :
template<class T>
void BinarySearchTree<T>::BSTreeHelper(int low, int high, T* elems, BTNode<T>* root) {
int mid = (low+high)/2; // to get the middle value
bool isEqual = (low+1 == high || high-1 == low);
// if there is a middle value, insert it
if (!isEqual) {
BTNode<T>* nodePtrL = new BTNode<T>;
root->left = nodePtrL;
BSTreeHelper(low, mid, elems, nodePtrL);
BTNode<T>* nodePtrR = new BTNode<T>;
root->right = nodePtrR;
BSTreeHelper(mid, high, elems, nodePtrR);
root->elem = elems[mid];
cout << "Inserted Element = " << root->elem << endl;
}
}
/* A lightweight structure implementing a general binary tree node */
template <class T>
struct BTNode {
T elem; // element contained in the node
BTNode *left; // pointer to the left child (can be NULL)
BTNode *right; // pointer to the right child (can be NULL)
// Constructors
BTNode() { left = right = NULL; }
BTNode(T elem, BTNode* left = NULL, BTNode* right = NULL) {
this->elem = elem;
this->left = left;
this->right = right;
}
BTNode(const BTNode& src) {
this->elem = src.elem;
this->left = src.left;
this->right = src.right;
}
// Simple tests
bool is_leaf() const { return (left == NULL && right == NULL); }
};
이 I 쓴 함수이고 나는 어떤 식 으로든 isEqual 검사를 다르게하기 위해 머리를 감싸는 것처럼 보일 수 없다. 첫 번째 요소와 마지막 요소, 그리고 왜 여분의 노드가 가비지 값 (어레이의 범위를 벗어날 가능성이 가장 높은 값)으로 생성되는지 알 수 없습니다. 제공 할 수있는 도움에 감사드립니다. 이것은 과제이기 때문에 답을주고 싶지는 않지만 올바른 방향의 요점은 매우 높이 평가됩니다!