Construct an AVL tree from inserting the values 5, 2, 9, 6, 3, 8, 1 in that order. How many total rotations are needed during the construction of the tree to keep it balanced? A. 0 B. 1 C. 2 D. 3 E. 4
时间: 2023-12-03 10:45:06 浏览: 102
To construct an AVL tree from inserting the values 5, 2, 9, 6, 3, 8, 1 in that order, we start with the root node 5 and then insert each subsequent node according to the rules of an AVL tree.
First, we insert 2 as the left child of 5, resulting in an imbalance. We perform a right rotation to balance the tree:
```
5
/
2
```
becomes
```
2
\
5
```
Next, we insert 9 as the right child of 5, resulting in an imbalance. We perform a left rotation to balance the tree:
```
2
\
5
\
9
```
becomes
```
2
\
9
/
5
```
Next, we insert 6 as the left child of 9, resulting in an imbalance. We perform a right-left rotation to balance the tree:
```
2
\
9
/ \
6 10
```
becomes
```
2
\
6
\
9
\
10
```
Next, we insert 3 as the left child of 6, resulting in an imbalance. We perform a left-right rotation to balance the tree:
```
2
\
6
/ \
3 9
\
10
```
becomes
```
2
\
6
/ \
3 9
\
10
```
The tree is already balanced, so we do not need to perform any more rotations.
Therefore, the total number of rotations needed to keep the tree balanced during construction is 2, and the answer is C.
阅读全文