我想写递归遍历一个数组去,将值插入到一棵树,同时保持树平衡功能初始化一个平衡二叉搜索树。假设数组已经排序并且我们知道它的大小。我的理解是什么,我需要做的是来自各地的数组的中间开始,将该值插入根,然后采取左,右两半的中间,并将这些成左节点和根的权利,等等直到数组被填充。递归是首先想到的,我编码的内容是有意义的,但似乎并没有按照我的意图工作。我有从Array C++
问题是未插入第一个和最后一个值,而我在每片叶子的左侧和右侧获得垃圾值的节点,而不是他们的是NULL。
节点是简单的(由教师提供)的结构:
/* 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); }
};
这是我写的函数:用于构造
// ---------------------------------------------------------------------------
// 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;
}
}
我似乎无法以任何方式对isEqual检查做出不同的解释,以便说明问题第一个和最后一个元素,我真的不知道为什么额外的节点正在创建垃圾值(最有可能的数组边界之外的值)。感谢您的任何帮助,您可以提供。这是一项任务,所以我不想给出答案,但正确的方向点是非常感谢!