Professional Documents
Culture Documents
Trees
Trees
ELEMENTARYDATA STRUCTURES
data link
A B C D 0
/
1
front rear
if m > n.
...,xn,yn,yn+i,...,ym)
4. A double-ended queue (deque)is a linearlist for which insertionsand
deletionscan occurat eitherend.Show how to representa dequein a
one-dimensionalarray and write algorithmsthat insert and deleteat
eitherend.
5. Considerthe hypotheticaldata objectXI. The objectX2 is a linear
list with the restrictionthat althoughadditionsto the list can bemade
at eitherend, deletions can bemadefrom oneend only. Designa linked
list representation for XI. Specify initial and boundary conditions
for
your representation.
2.2 TREES
Definition2.1[Tree] A treeis a finite set of one or morenodessuch that
thereis a speciallydesignatednodecalledthe root and the remainingnodes
are partitionedinto n > 0 disjointsetsTi,... ,Tn,whereeachof thesesets
is a tree.ThesetsTi,... ,Tn arecalledthe subtreesof the root. \342\226\241
2.2. TREES 77
2.2.1 Terminology
Thereare many termsthat are often used when referringto trees.Consider
the treein Figure2.5.This treehas 13nodes, eachdataitemof a nodebeing
a singleletter for convenience.The root containsA (we usually say node
A), and we normally draw treeswith their rootsat the top.The numberof
subtreesof a nodeis calledits degree.The degreeof A is 3,of C is 1,and of
F is 0. Nodesthat have degreezeroarecalledleaf or terminalnodes.The
set {K,L, F, G, M, I, J} is the set of leafnodesof Figure2.5.The other
nodesare referredto as nonterminals.The rootsof the subtreesof a node
X art; the childrenof X. The node X is the parent of its children.Thus the
childrenof D are H, I, and J, and the parent of D is A.
Figure2.5A sampletree
Childrenof the sameparent are said to be siblings. For exampleH, I,
and J are siblings.We can extendthis terminology if we needto sothat we
can ask for the grandparentof M, which is D, and soon. The degreeof a
tree is the maximumdegreeof the nodesin the tree. Thetree in Figure2.5
has degree3.The ancestorsof a nodeareall the nodesalongthe path from
the root to that node.Theancestorsof M are A, D, and H.
The level of a nodeis defined by initially letting the rootbe at level one.
If a nodeis at level p, then its childrenare at level p + 1.Figure2.5shows
the levels of all nodesin that tree.The height or depth of a tree is defined
to be the maximumlevel of any nodein the tree.
A forestis a set of n > 0 disjointtrees.Thenotionof a forest is very close
to that of a treebecauseif we remove the root of a tree,we get a forest.For
example,in Figure2.5if we remove A, we get a forest with threetrees.
78 CHAPTER2. ELEMENTARYDATA STRUCTURES
A 0
i ' \" _
\302\273
B F 0 C G 0 D I J 0
' \302\273
E K L 0 H M 0
Figure2.6List representation
for the tree of Figure2.5
2.2.2 BinaryTrees
A binary tree is an important type of treestructurethat occursvery often.
It is characterized
by the fact that any nodecan have at most two children;
that is,thereis no nodewith degreegreaterthan two. Forbinary treeswe
distinguishbetweenthe subtreeon the left and that on the right, whereas
for othertreesthe orderof the subtreesis irrelevant.Furthermore a binary
tree is allowed to have zeronodeswhereasany other tree must have at least
one node.Thus a binary tree is really a different kind of objectthan any
othertree.
Definition2.2A binary tree is a finite set of nodesthat is eitherempty
or consistsof a root and two disjoint binary treescalledthe left and right
subtrees. \342\226\241
level
(a)
This representation can clearly be used for all binary trees though in
most casesthere is a lot of unutilizedspace.For completebinary trees
the representationis idealas no spaceis wasted. For the skewed tree of
Figure 2.7,however, lessthan a third of the array is utilized.In the worst
casea right-skewedtree of depth k requires2k 1locations. Of theseonly
\342\200\224
k are occupied.
Although the sequentialrepresentation, as in Figure2.9,appearsto be
good completebinary trees,
for it is wasteful for many otherbinary trees.
In
addition,the representationsuffers from the generalinadequacies of
representations.Insertionor deletionof nodesrequiresthe movement
sequential
2.3.DICTIONARIES 81
A B - C - - - D - .. . E
A B C D E F G H
... (16)
Figure2.9Sequentialrepresentation
of the binary treesof Figure2.7
2.3 DICTIONARIES
An abstractdata type that supportsthe operationsinsert,delete,and search
is calleda dictionary. Dictionaries
have found applicationin the designof
numerousalgorithms.
tree tree
A 0
A
\342\226\240
B 0
1
/ B \\ c
C0
\342\226\240
/ D \\ 0 E 0 0 F 0 0 G0
D0
\342\226\240
OHO 0 I 0
0 E 0
(a) (b)
Figure2.10Linked representations
for the binary treesof Figure2.7
2.3.DICTIONARIES 83
2.3.1 BinarySearchTrees
Definition2.3[Binary search tree]A binary searchtreeis a binary tree. It
may be empty. If it is not empty, then it satisfies the following properties:
1.Every elementhas a key and no two elementshave the samekey (i.e.,
the keys are distinct).
2. The keys (if any) in the left subtreeare smallerthan the key in the
root.
3. The keys (if any) in the right subtreeare largerthan the key in the
root.
4. The left and right subtreesarealsobinary searchtrees. \342\226\241
Figure2.11Binary trees
1 Algorithm Search(\302\243,:r)
2 { = 0) thenreturn0;
3 if (t
4 elseif (x = t data) thenreturnt;
-\302\273
8 }
1 AlgorithmISearch(:c)
2 1
3 found := false;
4 t :=tree;
5 while ((t 0) and notfound) do
y\302\243
6 {
7 if (x = (t data)) thenfound := true;
-\302\273
else
(\302\243
9 rchild);
10
\302\243:=(\302\243-\302\273
}
11 if (notfound) thenreturn0;
12 elsereturnt;
13 }
1 Algoriithm Searchk(fc)
2 {
3 found := false;t := tree;
4 while ((t 0) andnot fowid) do
y\302\243
5 {
6 if (& = thenfound := true;
leftsize))
elseif then := ->Ichild);
(\302\243-\302\273
7 leftsize)) \302\243
else
(&<(\302\243-\302\273 (\302\243
8
9 {
10 k := k (t -^ leftsize); \342\200\224
11 t := (t rchild); \342\200\224>
12 }
13 }
14 if (notfound) thenreturn0;
15 elsereturnt;
10 }
1 AlgorithmInsert(x)
2 // Insertx into the binary searchtree.
3 {
4 found :=false;
5 = tree;
6 for x. q is the parent of p.
pill Search
7
8
while
{
,
((p 0) andnot found) do /
9
10
Q '\342\226\240=
P'i
if (x = (p data)) thenfound :=true;
II Save p.
\342\200\224>
13 }
14 // Performinsertion.
15 if ( not found) then
16 {
17 p := new TreeNode;
18 (p ->Ichild) :=0; (p ->rchild) := 0; (p ->data) := j;;
19
20
if
{
(tree / 0) then
21 data)) then(g ->Ichild):=p;
if (x < (q \342\200\224>
25 }
26 }
2.3.2 CostAmortization
Supposethat a sequenceII,12,Dl,13,14,15,16,D2,17of insert and delete
operationsis performedon a set.Assume that the actual costof eachof the
seven insertsis one. (We usethe termscostand complexityinterchangeably.)
By this, we mean that eachinsert takesone unit of time. Further, suppose
that the deleteoperationsDl and D2 have an actualcostof eight and ten,
respectively.So, the totalcostof the sequenceof operationsis 25.
In an amortization schemewe chargesomeof the actualcostof an
to otheroperations.
operation This reducesthe chargedcostof someoperations
and increasesthat of others.Theamortized costof an operationis the total
costchargedto it. Thecosttransferring(amortization)schemeis required
to be such that the sum of the amortizedcostsof the operationsis greater
than or equal to the sum of their actualcosts. If we chargeone unit of the
costof a deleteoperationto eachof the insertssincethe last deleteoperation
(if any), then two units of the cost of Dl get transferredto II and 12(the
chargedcostof eachincreasesby one), and four units of the costof D2 get
transferredto 13to 16.Theamortizedcostof eachof II to 16becomestwo,
that of 17becomes equal to its actualcost (that is,one), and that of eachof
Dl and D2 becomes6. The sum of the amortizedcostsis 25, which is the
sameas the sum of the actualcosts.
Now supposewe can prove that no matter what sequenceof insert and
deleteoperationsis performed,we can chargecostsin such a way that the
amortizedcostof eachinsertionis no morethan two and that of eachdeletion
90 CHAPTER2. ELEMENTARYDATA STRUCTURES
EXERCISES
1.Write an algorithmto deletean elementre from a binary searchtree t.
What is the timecomplexity
of your algorithm?
2. Presentan algorithm to start with an initially empty binary search
tree and maken random insertions.Usea uniform randomnumber
generatorto obtain the values to be inserted.Measurethe height of
the resultingbinary searchtree and divide this height by log2 n. Do
this for n = 100, 500,1,000,2,000, 3,000,... , 10,000.Plot the ratio
height/log2 n as a function of n. Theratio should be approximately
constant (around 2).Verify that this is so.
3. Supposethat eachnode in a binary searchtree also has the field
leftsizeas describedin the text. Designan algorithm to insert an
elementx into sucha binary searchtree. Thecomplexity of your
algorithm should be O(h), whereh is the height of the searchtree. Show
that this is the case.
4. Do Exercise3,but this timepresentan algorithmto deletethe element
with the fcth-smallestkey in the binary searchtree.
5. Find an efficient data structurefor representing a subset S of the
integers from 1 to n. Operations w e wish to performon the set are
\342\200\242
to insert the integeri to the set S.If i is already in
INSERT(i)
the set,this instructionmust be ignored.
\342\200\242
DELETEto deletean arbitrary memberfrom the set.
\342\200\242