Professional Documents
Culture Documents
Lecture 16
Lecture 16
C++ code, and discuss the structure of a BST class. We will also use tree diagrams
to illustrate the deletion process.
**Example BST**:
```
50
/ \
30 70
/ \ / \
20 40 60 80
```
**Steps**:
1. Replace 50 with 60.
2. Delete node 60.
**Resulting BST**:
```
60
/ \
30 70
/ \ \
20 40 80
```
Here is a C++ implementation of the remove function and the BST class.
```cpp
#include <iostream>
using namespace std;
struct TreeNode {
int value;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : value(x), left(nullptr), right(nullptr) {}
};
class BST {
public:
TreeNode* root;
BST() : root(nullptr) {}
void inorder() {
inorderRec(root);
}
private:
TreeNode* insertRec(TreeNode* node, int key) {
if (node == nullptr)
return new TreeNode(key);
return node;
}
int main() {
BST bst;
bst.insert(50);
bst.insert(30);
bst.insert(20);
bst.insert(40);
bst.insert(70);
bst.insert(60);
bst.insert(80);
return 0;
}
```
### Explanation
1. **Insertion**:
- The `insertRec` function inserts a node in the BST while maintaining the BST
property.
- It places the new node in the correct position based on the value.
2. **Deletion**:
- The `removeRec` function handles node deletion.
- It identifies the node to be deleted, handles the three cases (leaf node, one
child, two children), and updates the tree structure accordingly.
3. **Inorder Traversal**:
- The `inorderRec` function prints the values of nodes in ascending order (left,
root, right).
| Concept | Description
| Example Traversal/Operation
|
|-----------------------|-----------------------------------------------------------
--------------------------------------|---------------------------------------------
-----------|
| Insertion | Adds a node to the BST while maintaining its properties
| Insert 50, 30, 70, 20, 40, 60, 80
|
| Deletion (Node=50) | Removes a node while maintaining BST properties; handles
three main cases | Deletes 50, replaces with 60, resulting in
`60, 30, 70, 20, 40, 80` |
| Inorder Traversal | Visits nodes in ascending order (left, root, right)
| `20, 30, 40, 50, 60, 70, 80` before deletion
|
| BST Class Structure | Defines the BST class with insertion, deletion, and
traversal functions | `class BST { public: TreeNode* root;
... }` |
Feel free to ask for more details or any specific parts you'd like to delve deeper
into!