Lecture 7: Binary Trees - II#
Review#
dynamic operations on binary search tree mostly requires \(O(h)\) time
the minimum \(h\) of a tree of \(n\) nodes is \(logn\)
dynamic operations such as insertion may lead to the height of a tree way larger than \(logn\), which then increase operation time
the extreme case is that new items are being added in ascending order, the tree will be one long branch off to the right, with height of \(n\)
this lecture shows how to
balance the height
of binary tree
Height Balance#
how to maintain height \(h = O(logn)\) where n is the number of nodes in the tree?
a binrayr tree that maintains \(O(logn)\) height under dynamic operations is called
balanced
.many algorithms
such as
AVL
tree
Rotation#
need reduce height of tree without changing its traversal order so that we represent the same sequence of items
Rotations!
A rotation relinks \(O(1)\) ppinters to modify tree structure and maintains traversal order
AVL Tree#
AVL Trees maintain height-balance
A node is height-balanced if heights of its left and right subtrees differ by at most 1
let
skew
of a node be theheight of its right subtree minus that of its left subtree
then a node is height-balanced if its skew is -1, 0, or 1
Computing Height#
how to tell wether a node is height-balanced? compute the height of subtrees!!
algorithm
recusively compute the height of left subtree and right subtree of node <X>
add 1 to the max of the two heights
run in \(O(n)\) time since we recurse on every node
can we improve to \(O(1)\)? -> tree augumentation: augument each node with the height of its subtree !!
the height of <X> can be computed in \(O(1)\) time from the heights of its children
look up the stored height of left and right child in \(O(1)\)
add 1 to the max of the two
during dynamic operaiton, the height and other augumentation of each node must be maintained as the tree changes shape
update relinked nodes in a rotation operation in \(O(1)\) time
update all ancestors of an inserted or deleted node in \(O(h)\) time by walking up the tree.