Sei sulla pagina 1di 19

3.

1 Height-Balanced Trees
3.2 Weight-Balanced Trees

Chen
Song
Height-Balanced Trees
Height-Balanced Trees

Height The maximum length of any path from the


root to a leaf.

Height-Balanced Tree
In each interior node, the height of the right su
btree and left subtree differ by at most one.
Height-Balanced Trees

Example:
Height-Balanced Trees

Theorem
A height-balanced tree of height h has at least
( (
leaves.
Height-Balanced Trees

Tree T

h-2
h-1

Tree T has at least leaves:


leaves(h)=leaves(h-1)+leaves(h-2)
leaves(0)=1
leaves(1)=2
Characteristic equation:
xh=xh-1+xh-2 => x2-x-1=0
Height-Balanced Trees

Insert and Delete

After insert or delete:


Case 1: Tree is still balanced
Case 2: Tree is not balanced at node n
|n->left-height n->right-height|=2
Height-Balanced Trees

1. n->left->height = n->right->height+2 and


n->left->left->height=n->right->height+1
Right rotation on node n

2. n->left->height = n->right->height+2 and


n->left->left->height=n->right-height
Left rotation on node n->left, and follow right rot
ation on node n
Height-Balanced Trees

3. n-> right->height = n->left->height+2 and


n->right->right->height=n->left->height+1
Left rotation on node n->left

4. n->right->height = n->left->height+2 and


n->right->right->height=n->left-height
Right rotation on node n->right, and follow left ro
tation on node n
Height-Balanced Trees

Height-Balanced Tree structure supports search, insert, and delete


in O(logn) time

Search => O(logn)


Insert => search + insert + rebalance => O(logn)
O(logn) O(1) O(logn)

Delete => search + delete + rebalance => O(logn)


O(logn) O(1) O(logn)
Weight-Balanced Trees
Weight-Balanced Trees

Weight
The number of leaves of a tree.

Weight-Balanced Tree
The weight of the right and left subtree in each
node differ by at most one.
Weight-Balanced Trees

-weight-balanced trees
For each subtree, the left and right sub-subtrees
has each at least a fraction of of total weight of the
subtree.
Tree T:

WTWT1(1-)WT
T2 WTWT2(1-)WT
T1
Weight-Balanced Trees

Theorem
An -weight-balanced tree of height h2 has at l
east
leaves.
Weight-Balanced Trees

Rebalance
n is current node []

Case 1:
n->left->weight *n->weight and
n->right->weight *n->weight
No rebalancing
Weight-Balanced Trees

Case
2:
n->right->weight *n->weight
If n->left->left->weight > (+)n->weight,
do right rotation on node n
Else left rotation on n->left, followed right rotation o
n
node n.
2-2+
Weight-Balanced Trees

Case 3:
n->left->weight *n->weight
If n->right->right->weight > (+)n->weight,
do left rotation on node n
Else right rotation on n->right, followed left rotation
on node n.
Weight-Balanced Trees

Theorem
The weight-balanced tree structure supports search, insert,
and delete in O(logn) time.

Search => O(logn)


Insert => search + insert + rebalance => O(logn)
O(logn) O(1) O(logn)

Delete => search + delete + rebalance => O(logn)


O(logn) O(1) O(logn)
END

Potrebbero piacerti anche