Binary trees Binary trees David Morgan Binary trees Binary trees � elements have up to 2 child elements � left child sorts less, right more, than parent � tree has a depth � tree has a balance, comparing depths of its left and right trees (greater difference, less balance) 1
Binary tree of months, Binary tree of months, for days- -per per- -month determination month determination for days jan 31 feb 28 mar 31 apr 30 jun 30 may 31 aug 31 jul 31 sep 30 dec 31 oct 31 Depth: 4 nov 30 Max comparisons: 6 Average comparisons: 3.5 input sequence: jan, feb, mar, apr, may, june, july, aug, sept, oct, nov, dec (chronological) A skewed tree A skewed tree apr 30 aug 31 dec 31 feb 28 jan 31 jul 31 jun 30 mar 31 may 31 nov 30 Depth: 12 search cost O(N) oct 31 12 elements � 12 comparisons Max comparisons: 12 N elements � N comparisons Average comparisons: 6.5 sep 30 input sequence: apr, aug, dec, feb, jan, july, june, mar, may, nov, oct, sept (alphabetical) 2
A balanced tree A balanced tree jul 31 feb 31 may 31 aug 31 jan 31 mar 31 oct 31 apr 31 dec 31 jun 31 nov 31 sep 31 search cost O(log N) 2 levels � 3 elements � 2 comparisons 3 levels � 7 elements � 3 comparisons 4 levels � 15 elements � 4 comparisons Depth: 4 L levels � 2 L -1 elements � L comparisons, or Max comparisons: 4 log(N+1) levels � N elements � log(N+1) comparisons Average comparisons: 3.1 input sequence: july, feb, may, aug, dec, mar, oct, apr, jan, june, sept, nov Binary tree of last names, Binary tree of last names, for data record determination for data record determination jacobs 7 brown 6 jones 2 anders 5 miller 1 smith 4 Database Recno name rank serial no 1 miller corporal 4-139 2 jones major 3-209 3 baker private 7-981 4 smith lieutenant 3-101 5 anders private 8-388 6 brown sargeant 8-231 7 jacobs captain 6-495 8 johnson general 4-556 3
Tree balance Tree balance � depends on insertion sequence � balance achievable independent of sequence, by performing mid-course re-balancing � during insertion, whenever an insertion upsets the balance, re-balance dynamically before inserting next element � tree never gets unbalanced, so final result is always balanced Building tree, no rebalancing Building tree, no rebalancing insert 1 insert 2 insert 3 insert 4 insert 5 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5 input sequence: 1, 2, 3, 4, 5 final tree unbalanced 4
Building tree, mid- Building tree, mid -course re course re- -balancing balancing insert 5 insert 1 insert 2 insert 3 insert 4 2 2 1 1 1 1 3 1 3 2 2 4 4 3 5 re-balance re-balance 2 2 1 3 1 4 3 5 input sequence: 1, 2, 3, 4, 5 final tree balanced 5
Recommend
More recommend