Lecture 33 - Nov 28, 2023
Last lecture
Introduction to trees, binary trees and binary search trees.
Search.
Today
Recursive print and insert operations in binary search trees.
Recursive print and insert in BST
8
/ \
4 10
/ \ \
1 6 12
class BSTNode {
private:
int value;
*left, *right;
BSTNode
public:
(int v) {
BSTNode;
value v= right = NULL;
left }
~BSTNode() {
delete left;
delete right;
}
int getValue() {
return value;
}
*getLeft() {
BSTNode return left;
}
*getRight() {
BSTNode return right;
}
void setLeft(BSTNode *l) {
= l;
left }
void setRight(BSTNode *r) {
= r;
right }
};
class BSTree {
private:
* root;
BSTNode
bool searchNode(int v, BSTNode* n) {
if (n == NULL) {
return false;
} else if (n->getValue() == v) {
return true;
} else if (n->getValue() > v) {
return searchNode(v, n->getLeft());
} else {
return searchNode(v, n->getRight());
}
}
void insertHelper(int v, BSTNode* n);
void printInOrderHelper(BSTNode* n);
public:
() {
BSTree= NULL;
root }
~BSTree() {
delete root;
}
* getRoot() {
BSTNodereturn root;
}
bool search(int v) {
return searchNode(v, root);
}
void insert(int v);
void printInOrder();
};
void BSTree::insertHelper(int v, BSTNode* n) {
if (n->getValue() == v) {
return; // no two nodes have the same value
} else if (v < n->getValue()) {
if (n->getLeft() == NULL) {
->setLeft(new BSTNode(v)); // insert to the left of a leaf node
n} else {
(v, n->getLeft());
insertHelper}
} else {
if (n->getRight() == NULL) {
->setRight(new BSTNode(v)); // insert to the right of a leaf node
n} else {
(v, n->getRight());
insertHelper}
}
}
void BSTree::printInOrderHelper(BSTNode* n) {
if (n != NULL) {
(n->getLeft());
print<< n->getValue() << " ";
cout (n->getRight());
print}
}
print(8)
|- print(4)
| |- print(NULL)
| |- cout << 4
| |- print(6)
| |- print(NULL)
| |- cout << 6
| |- print(NULL)
|- cout << 8
|- print(10)
|- print(NULL)
|- cout << 10
|- print(NULL)
void BSTree::printInOrder() {
return printInOrderHelper(root);
}
We may print the BST in different orders
void BSTree::printPreOrderHelper(BSTNode* n) {
if (n != NULL) {
<< n->getValue() << " ";
cout (n->getLeft());
printPreOrder(n->getRight());
printPreOrder}
}
| 8 | 4 | 6 | 10 |
prints node
first, then left
, then right
subtree
void BSTree::printPostOrderHelper(BSTNode* n) {
if (n != NULL) {
(n->getLeft());
printPostOrder(n->getRight());
printPostOrder<< n->getValue() << " ";
cout }
}
| 6 | 4 | 10 | 8 |
prints left
subtree first, then right
, then node
Homework: Implement minValueNode
and maxValueNode
.
* BSTree::minValueNode(BSTNode* n) {
BSTNodereturn minValueNodeHelper(n->getLeft());
}