05 Leftist Heaps
05 Leftist Heaps
05 Leftist Heaps
1
Are leftist trees always…
0 0 0 0
– complete?
0 0 1
– balanced?
2 0 0 0
0
1 1 0
Consider a subtree of a leftist tree…
0
1 0 0 0 0 – is it leftist?
0
0 0 0
7
Right Path in a Leftist Tree is Short (#1) Right Path in a Leftist Tree is Short (#2)
Claim: The right path (path from root to rightmost Claim: If the right path has r nodes, then the tree has
leaf) is as short as any in the tree. at least 2r-1 nodes.
Proof: (By contradiction)
Pick a shorter path: D1 < D2
Proof: (By induction)
Say it diverges from right path at x x Base case : r=1. Tree has at least 21-1 = 1 node
Inductive step : assume true for r-1. Prove for tree with right
npl(L) ≤ D1-1 because of the path of path at least r.
L R 1. Right subtree: right path of r-1 nodes
length D1-1 to null D1 D2 ⇒ 2r-1-1 right subtree nodes (by induction)
2. Left subtree: also right path of length at least r-1 (prev. slide)
npl(R) ≥ D2-1 because every node on
⇒ 2r-1-1 left subtree nodes (by induction)
right path is leftist
Why do we have the leftist property? Merge two heaps (basic idea)
Because it guarantees that: • Put the root with smaller value as the new
• the right path is really short compared to root.
the number of nodes in the tree • Hang its left subtree on the left.
• A leftist tree of N nodes, has a right path of • Recursively merge its right subtree and the
other tree.
at most log2(N+1) nodes
• Before returning from recursion:
– Update npl of merged root.
Idea – perform all work on the right path – Swap left and right subtrees just below root, if
needed, to keep leftist property of merged
11
result. 12
Merging Two Leftist Heaps Merge Continued
Recursive calls to merge(T1,T2): returns one
leftist heap containing all elements of the two a a If npl(R’) > npl(L1) a
merge
…
(distinct) leftist heaps T1 and T2
merge L1 R1 L1 R’ R’ L1
T1 a a R’ = merge(R1, T2)
merge b
L1 R1 L1
a<b R1 L2 R2
T2 b b
Note special case: merge(null, T) = merge(T, null) = T
L2 R2 L2 R2 13 runtime: 14
15 0 15 0 15 0
17 18