Vous êtes sur la page 1sur 3

Definitions

The height of a binary tree is the maximum path length from the root to a leaf. A singlenode binary tree has height 0, and an empty binary tree has height -1. As another
example, the following binary tree has height 3.
7
/

12

10
/

20
\

11

An AVL tree is a binary search tree in which every node is height balanced, that is, the
difference in the heights of its two subtrees is at most 1. The balance factor of a node
is the height of its right subtree minus the height of its left subtree. An equivalent
definition, then, for an AVL tree is that it is a binary search tree in which each node has
a balance factor of -1, 0, or +1. Note that a balance factor of -1 means that the subtree
is left-heavy, and a balance factor of +1 means that the subtree is right-heavy. For
example, in the following AVL tree, note that the root node with balance factor +1 has a
right subtree of height 1 more than the height of the left subtree. (The balance factors
are shown at the top of each node.)
The following binary search tree is not an AVL tree. Notice the balance factor of -2 at
node 70.
-1
100
/

-2
70
/

+1
30
/

0
80
\
-1
40
/

0
36

+1
130

0
180
\

0
10

-1
150

0
140

Inserting a New Item


Initially, a new item is inserted just as in a binary search tree. Note that the item always goes
into a new leaf. The tree is then readjusted as needed in order to maintain it as an AVL tree.
There are three main cases to consider when inserting a new node.

Case 1:
A node with balance factor 0 changes to +1 or -1 when a new node is inserted below it. No
change is needed at this node. Consider the following example. Note that after an insertion one
only needs to check the balances along the path from the new leaf to the root.

0
40
/

+1
20

0
50
\

/
0
30

0
45

0
70

After inserting 60 we get:


+1
40
/

+1
20

+1
50
\

/
0
30

0
45

-1
70
/
0
60

Case 2:
A node with balance factor -1 changes to 0 when a new node is inserted in its right subtree.
(Similarly for +1 changing to 0 when inserting in the left subtree.) No change is needed at this
node. Consider the following example.

-1
40
/

+1
20
/

0
50
\

0
10

/
0
30

0
45

0
70

0
22

0
32

After inserting 60 we get:


0 <-- the -1 changed to a 0 (case 2)
40
/

+1
20
/

+1 <-- an example of case 1


50
\

0
10

0
30

/
0
22

/
0
45

\
0
32

/
0
60

-1 <-- an example of case 1


70

Vous aimerez peut-être aussi