Professional Documents
Culture Documents
BST
BST
//Helping functions
2.
int height(BSTNode* root) {
if (root == 0) {
return 0;
}
int l = height(root->left);
int r = height(root->right);
if (l > r) {
return l + 1;
}
else {
return r + 1;
}
}
3.
void supFunc(BSTNode* root, vector<int>& arr) {
if (root == NULL) {
return;
}
supFunc(root->left, arr);
arr.push_back(root->val);
supFunc(root->right, arr);
}
4.
void supFunc(BTNode* root, int lo, int hi, int& count) {
if (root == NULL) {
return;
}
if (root->val >= lo && root->val <= hi) {
count++;
}
supFunc(root->left, lo, hi, count);
supFunc(root->right, lo, hi, count);
}
int rangeCount(BTNode* root, int lo, int hi) {
int count = 0;
supFunc(root, lo, hi, count);
return count;
}
5.
int singleChild(BSTNode* root) {
// STUDENT ANSWER
if (root == NULL) {
return 0;
}
int count = 0;
if ((root->left == NULL && root->right != NULL) || (root->left != NULL && root-
>right == NULL)) {
count ++;
}
count += singleChild(root->left);
count += singleChild(root->right);
return count;
}
6.
BSTNode* subtreeWithRange(BSTNode* root, int lo, int hi) {
// STUDENT ANSWER
if (root == NULL) {
return NULL;
}
if (root->val < lo) {
return subtreeWithRange(root->right, lo, hi);
}
else if (root->val > hi) {
return subtreeWithRange(root->left, lo, hi);
}
else {
root->left = subtreeWithRange(root->left, lo, hi);
root->right = subtreeWithRange(root->right, lo, hi);
return root;
}
}
7.
// STUDENT ANSWER BEGIN
// You can define other functions here to help you.
bool find(T i) {
// TODO: return true if value i is in the tree; otherwise, return false.
if (root == NULL) {
return 0;
}
Node* itr = root;
while (true) {
if (i == itr->value) {
return 1;
}
if (i < itr->value) {
if (itr->pLeft != NULL) {
itr = itr->pLeft;
} else {
return 0;
}
} else {
if (itr->pRight != NULL) {
itr = itr->pRight;
} else {
return 0;
}
}
}
}
T sum(T l, T r) {
// TODO: return the sum of all element in the tree has value in range [l,r].
int sum = 0;
supFunc(root, l, r, sum);
return sum;
}
// STUDENT ANSWER END
8.
// STUDENT ANSWER BEGIN
// You can define other functions here to help you.
T getMin() {
//TODO: return the minimum values of nodes in the tree.
Node* itr = root;
while (itr->pLeft != NULL) {
itr = itr->pLeft;
}
return itr->value;
}
T getMax() {
//TODO: return the maximum values of nodes in the tree.
Node* itr = root;
while (itr->pRight != NULL) {
itr = itr->pRight;
}
return itr->value;
}