Files
G4G0-2/Data Structures/GPT Answers to Past Paper/Question 10.md
2024-12-01 23:50:59 +00:00

59 lines
1.9 KiB
Markdown

To insert a node into a **binary search tree (BST)** while keeping the tree **balanced**, we need to perform the following steps:
1. **Insert the node** in the appropriate place according to the **BST properties** (left child < parent < right child).
2. After insertion, **rebalance the tree** (if necessary) to ensure that it remains balanced. A tree is considered balanced if the height difference between the left and right subtrees of any node is at most 1 (this is the **balanced binary tree** or **AVL tree** property).
### **Given Binary Search Tree**:
```
10
/ \
5 15
/ / \
2 12 20
```
### **Step 1: Insert 4 into the BST**
We start by inserting **4** into the BST:
- 4 is less than 10, so we move to the left of 10.
- 4 is less than 5, so we move to the left of 5.
- 4 is greater than 2, so 4 will be placed as the **right child** of 2.
After insertion, the tree looks like this:
```
10
/ \
5 15
/ / \
2 12 20
\
4
```
### **Step 2: Balance the Tree (If Needed)**
At this point, the tree is not balanced. Let's check the balance factors of the nodes:
- **Node 2** has a left subtree height of 0 and a right subtree height of 1. Its balance factor is `0 - 1 = -1`, which is acceptable.
- **Node 5** has a left subtree height of 1 and a right subtree height of 1. Its balance factor is `1 - 1 = 0`, which is balanced.
- **Node 10** has a left subtree height of 2 (because of nodes 5, 2, and 4) and a right subtree height of 2 (because of nodes 15, 12, and 20). Its balance factor is `2 - 2 = 0`, which is balanced.
Since the tree is balanced at all levels, **no further rebalancing is necessary**.
### **Final Balanced Tree**:
The final tree after inserting 4 is:
```
10
/ \
5 15
/ / \
2 12 20
\
4
```
### **Conclusion**:
After inserting 4, the tree remains balanced and no rotations are needed.