binary trees complete lesson

Upload: dyahcitta

Post on 07-Aug-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/19/2019 Binary Trees Complete Lesson

    1/29

    Binary Trees

    Chapter 11

    Binary TreesThe data structures presented so far are predominantly linear. Every element has one unique

     predecessor and one unique successor (except the first and last elements). Arrays, and singly linked

    structures used to implement lists, stacks, and queues all have this distinctive linear characteristic. The

    tree structure presented in this chapter is a hierarchical data structure where each node may have more

    than one successor.

    Goals

    • ecome familiar with tree terminology and some uses of trees

    • !tore data in a hierarchical data structure as a "ava #ollection class

    • $mplement %inary tree algorithms

    • $mplement algorithms for a inary !earch Tree

    11.1 TreesTrees are often used to store large collections of data in a hierarchical manner where elements are

    arranged in successive levels. &or example, file systems are implemented as a tree structure with theroot directory at the highest level. The collection of files and directories are stored as a tree where a

    directory may have files and other directories. Trees are hierarchical in nature as illustrated in this

    view of a very small part of a file system (the root directory is signified as ').

     

    . . . . . .

    . . . . . .

    /

    bin

    test sleep

    etc.Spotlight-V100

    sync nanorc mail.rc

    Each node in a tree has exactly one parent except for the distinctive node known as the root. hereasthe root of a real tree is usually located in the ground and the leaves are a%ove the root, computer 

    223

  • 8/19/2019 Binary Trees Complete Lesson

    2/29

     Chapter 11

    scientists draw trees upside down. This convention allows us to grow trees down from the root since

    most people find it more natural to write from top to %ottom. ou are more likely to see the root at the

    *top* with the leaves at the *%ottom* of trees. Trees implemented with a linked structure can %e pictured

    like this+

     

    root

    edges

    2

    4

    3

    1

    !

    nodes

    leaves

    A tree is a collection of nodes with one node designated as the root. Each node contains a reference to

    an element and has edges connecting it to other nodes, which are also trees. These other nodes are

    called children. A tree can %e empty    have no nodes. Trees may have nodes with two or more

    children.A leaf  is a node with no children. $n the tree a%ove, the nodes with , -, and are leafs. All nodes

    that are not leaves are called the internal nodes of a tree, which are /, 0, and 1 a%ove. A leaf node

    could later grow a nonempty tree as a child. That leaf node would then %ecome an internal node. Also,

    an internal node might later have its children %ecome empty trees. That internal node would %ecome a

    leaf.

    A tree with no nodes is called an empty tree. A single node %y itself can %e considered a tree. A

    structure formed %y taking a node 2 and one or more separate trees and making 2 the parent of all

    roots of the trees is also a tree. This recursive definition ena%les us to construct trees from existing

    trees. After the construction, the new tree would contain the old trees as subtrees. A su%tree is a tree

     %y itself. y definition, the empty tree can also %e considered a su%tree of every tree.All nodes with the same parent are called siblings. The level of a node is the num%er of edges it

    takes to reach that particular node from the root. &or example, the node in the tree a%ove containing Jis at level 0. The height of a tree is the level of the node furthest away from its root. These definitions

    are summari3ed with a different tree where the letters " through # represent the elements.

    root "internal no$es " B %lea&es ' ( C G ) #height 3le&el o* root 0le&el o* no$e +ith ( 2no$es at le&el 1 3parent o* G, ) an$ # %chil$ren o* B ' ( 

    224

    Empty trees are

    shown here as /

  • 8/19/2019 Binary Trees Complete Lesson

    3/29

    Binary Trees

    A binary tree is a tree where each node has exactly two %inary trees, commonly referred to as the left

    child and right child. oth the left or right trees are also %inary trees. They could %e empty trees. hen

     %oth children are empty trees, the node is considered a leaf. 4nder good circumstances, %inary trees

    have the property that you can reach any node in the tree within log 0n steps, where n is the num%er of 

    nodes in the tree.

    '-pression TreeAn expression tree is a %inary tree can %e used to store an arithmetic expression. The tree can then %e

    traversed to evaluate the expression. The following expression is represented as a %inary tree with

    operands as the leaves and operators as internal nodes.

    (1 + (5 + (2 * 3))) / 3

    5epending on how you want to traverse this tree    visit each node once    you could come up with

    different orderings of the same expression+ infix, prefix, or postfix. These tree traversal algorithms are

     presented later in this chapter.

    Binary Search Tree

    Binary Search Trees  are %inary trees with the nodes arranged according to a specific ordering property. &or example, consider a %inary search tree that stores Integer elements. At each node, the

    value in the left child is less than the value of the parent. The right child has a value that is greater thanthe value of its parent. Also, since the left and right children of every node are %inary search trees, the

    same ordering holds for all nodes. &or example, all values in the left su%tree will %e less than the value

    in the parent. All values in the right su%tree will %e greater than the value of the parent.

    225 

  • 8/19/2019 Binary Trees Complete Lesson

    4/29

     Chapter 11

    The left child of the root (referenced %y A) has a value (-) that is less than the value of the root (6).

    7ikewise, the value of the right child of the root has a value (/8) that is greater than the root9s value

    (6). Also, all the values in the su%tree referenced %y A (, -, :), are less than the value in the root (6).

    To find the node with the value /8 in a %inary search tree, the search %egins at the root. $f the search

    value (/8) is greater than the element in the root node, search the %inary search tree to the right. !ince

    the right tree has the value you are looking for, the search is successful. $f the key is further down the

    tree, the search keeps going left or right until the key is found or the su%tree is empty indicating the

    key was not in the !T. !earching a %inary search tree can %e ;(log n) since half the nodes areremoved from the search at each comparison. inary search trees store large amounts of real world

    data %ecause of their fast searching, insertions, and removal capa%ilities. The %inary search tree will %e

    explored later in this chapter.

    )**man Tree

    5avid

  • 8/19/2019 Binary Trees Complete Lesson

    5/29

    Binary Trees

     

    'a'

    't'

    '_' 'e'

    'h' 'r'

    ith the convention that 8 means go left and / right, the letters have the following codes+

    'a' 01

    '_' 10

    'e' 11

    't' 000

    'h' 0010'r' 0011

    $nstead of storing 6 %its for each character, the most frequently occurring letters uin this example use

    only 0 or 1 %its. !ome of the characters in a typical file would have codes for some characters that aremuch longer than 6 %its. These 1/ %its represent a text file containing the test tea@at@three.

    0001101100100010000001000111111

    | | | | | | | | | | | |

      t e a  _  a  t _ t h r e e

    Assuming 6 %it A!#$$ characters, these 1/ %its would require /0B6 or = %its.

    11.2 #mplementing Binary TreesA %inary tree can %e represented in an array. ith an arrayC%ased implementation, the root node will

    always %e positioned at array index 8. The root9s left child will %e positioned at index /, and the right

    child will %e positioned at array index 0. This %asic scheme can %e carried out for each successive

    node counting up %y one, and spanning the tree from left to right on a levelCwise %asis.

    227 

    0

    1

    2

    3

    4

    !

    /

      0

      1  2

    %

     "

    %

    % " %

      4 !

    nll

    nll

  • 8/19/2019 Binary Trees Complete Lesson

    6/29

     Chapter 11

     2otice that some nodes are not used. These unused array locations show the holes in the tree. &or 

    example, nodes at indexes 1 and : do not appear in the tree and thus have the null value in the array.

    $n order to find any left or right child for a node, all that is needed is the node9s index. &or instance tofind node 09s left and right children, use the following formula+

    Left Child’s Index = 2 * Parent’s Index + 1

    Right Child’s Index = 2 * Parent’s Index + 2

    !o in this case, node 09s left and right children have indexes of - and respectively. Another %enefit of 

    using an array is that you can quickly find a node9s parent with this formula+

    Parent’s Index = (Child’s Index 1) / 2

    &or example, (-C/)'0 and (C/)'0 %oth have the same parent in index 0. This works, %ecause with

    integer division, '0 equals -'0.

    ine$ #mplementation

    inary trees are often implemented as a linked structure. hereas nodes in a singly linked structure

    had one reference field to refer to the successor element, a !ree"#de will have two references    one

    to the left child and one to the right child. A tree is a collection of nodes with a particular node chosen

    as the root. Assume the !ree"#de class will %e an inner class with private instance varia%les that store

    these three fields

    /. a reference to the element

    0. a reference to a left tree (another !ree"#de),

    1. a reference to a right tree (another !ree"#de).

    To keep things simple, the !ree"#de class %egins like this so it can store only strings. There are no

    generics (the BinarySearchTree class discussed later will use generics).

    $ri%ate &lass !ree"#de ' 

    $ri%ate tring data

      $ri%ate !ree"#de left

      $ri%ate !ree"#de right

      $uli& !ree"#de(tring eleentReferen&e) '

      data = eleentReferen&e

      left = null

      right = null

      ,

    ,

    These three lines of code (if in the same class as this inner node class) will generate the %inary tree

    structure shown+!ree"#de r##t = ne- !ree"#de(.!.)

    228 

  • 8/19/2019 Binary Trees Complete Lesson

    7/29

    Binary Trees

    r##tleft = ne- !ree"#de(.L.)

    r##tright = ne- !ree"#de(.R.)

    "T" 

    root

    "L"  "R" 

    229

  • 8/19/2019 Binary Trees Complete Lesson

    8/29

  • 8/19/2019 Binary Trees Complete Lesson

    9/29

    Binary Trees

      // 7ard de a tree #f si8e 9 #n : le%els

      $uli& %#id hardC#de0!ree() '

      r##t = ne- !ree"#de(.C.)

      r##tleft = ne- !ree"#de(.;.)

      r##tleftleft = ne- !ree"#de(.!.)

    r##tleftleftleft = ne- !ree"#de(..)

    r##tleftleftright = ne- !ree"#de(.R.)

      r##tleftright = ne- !ree"#de(.

  • 8/19/2019 Binary Trees Complete Lesson

    10/29

     Chapter 11

    hen a %inary tree is traversed in a preorder fashion, the root of the tree is visited before its children

     D its left and right su%trees. &or example, when $re#rderPrint is called with the argument r##t,

    the element C would first %e visited. Then a call is made to do a preorder traversal %eginning at the leftsu%tree. After the left su%tree has %een traversed, the algorithm traverses the right su%tree of the root

    node making the element G the last one visited during this preorder traversal.

     

    "C" 

    "G" "F" 

    root 

    "T" 

    "R" "B" 

    "K" 

    The following method performs a preorder traversal over the tree %uilt in the hardC#de0!ree

    method a%ove that has the string # in the root node. riting a solution to this method without

    recursion would require a stack and a loop. This algorithm is simpler to write with recursion.

    $uli& %#id $re6rderPrint() '

      $re6rderPrint(r##t)

      ,

      $ri%ate %#id $re6rderPrint(!ree"#de tree) '

      if (tree >= null) '

      // ?isit the r##t

      ste#ut$rint(treedata + . .)

      // !ra%erse the left sutree

      $re6rderPrint(treeleft)

      // !ra%erse the right sutree

      $re6rderPrint(treeright)

      ,

      ,

    hen the pu%lic method calls $re6rderPrint passing the reference to the root of the tree, the node

    with C is first visited. 2ext, a recursive call passes a reference to the left su%tree with F at the root.!ince this Tree2ode argument it is not null, F is visited next and is printed.

    232 

  • 8/19/2019 Binary Trees Complete Lesson

    11/29

    Binary Trees

     

    "C" 

    "G" "F" 

    root 

    "T" 

    "R" "B" 

    "K" 

    ?reorder Traversal so far+ C F

     2ext, a recursive call is made with a reference to the left su%tree of F with T at the root, which is

    visited %efore the left and right su%trees.

     

    "C" 

    "G" "F" 

    root 

    "T" 

    "R" "B" 

    "K" 

    Preorder Traversal so far C F T

    After the root is visited, another recursive call is made with a reference to the left su%tree B and it is

     printed. ecursive calls are made with %oth the left and right su%trees of . !ince they are %oth null,the if statement is false and the %lock of three statement is skipped. #ontrol returns to the method with

    T at the root where the right su%tree is passed as the argument.

    Preorder Traversal so far C F T B R

    The flow of control returns to visiting the right su%tree of F, which is ! . The recursive calls are then

    made for %oth of F*s children (empty trees). Again, in %oth calls, the %lock of three statements is

    skipped since tleft and tright are %oth null.

    233

  • 8/19/2019 Binary Trees Complete Lesson

    12/29

     Chapter 11

     

    "C" 

    "G" "F" 

    root 

    "T" 

    "R" "B" 

    "K"

     

    Preorder Traversal so far C F T B R K

    &inally, control returns to visit the right su%tree in the first call with the root as the parameter to visit

    the right su%tree in preorder fashion when G is printed.

    #nor$er Tra&ersal

    5uring an inorder traversal, each parent gets processed between 

    the processing of its left and rightchildren. The algorithm changes slightly.

    /. Traverse the nodes in the left su%tree inorder 0. ?rocess the root

    1. Traverse the nodes in the right su%tree inorder 

    $norder traversal visits the root of each tree only after its left su%tree has %een traversed inorder. The

    right su%tree is traversed inorder after the root.

      $uli& %#id in6rderPrint() '

      in6rderPrint(r##t)

      ,

      $uli& %#id in6rderPrint(!ree"#de t) '

      if (t >= null) '

      in6rderPrint(tleft)

      ste#ut$rint(tdata + . .)

      in6rderPrint(tright)

      ,

      ,

     2ow a call to in6rderPrint would print out the values of the following tree as

    B T R F K C G

    234

  • 8/19/2019 Binary Trees Complete Lesson

    13/29

    Binary Trees

     

    "C" 

    "G" "F" 

    root 

    "T" 

    "R" "B" 

    "K" 

    The in6rderPrint method keeps calling in6rderPrint recursively with the left su%tree. hen the

    left su%tree is finally empty, tleft==null, the %lock of three statements executed for B.

    5ostor$er Tra&ersal

    $n a postorder traversal, the root node is processed after  the left and right su%trees. The algorithm

    shows the process step after the two recursive calls.

    /. Traverse the nodes in the left su%tree in a postorder manner 

    0. Traverse the nodes in the right su%tree in a postorder manner 

    1. ?rocess the root

    A postorder order traversal would visit the nodes of the same tree in the following fashion+

      B R T K F G C

     

    "C" 

    "G" "F" 

    root 

    "T" 

    "R" "B" 

    "K" 

    The t#tring method of linear structures, such as lists, is straightforward. #reate one %ig string from

    the first element to the last. A t#tring method of a tree could %e implemented to return the elements

    concatenated in preC, inC, or postCorder fashion. A more insightful method would %e to print the tree to

    show levels with the root at the leftmost (this only works on trees that are not too %ig). A tree can %e

     printed sideways with a reverse inorder traversal. >isit the right, the root, and then the left.

    235 

  • 8/19/2019 Binary Trees Complete Lesson

    14/29

     Chapter 11

     

    C

      <

      ;

      R

      !

     

    The $rintide-as  method %elow does Gust this To show the different levels, the additional

     parameter de$th %egins at 8 to print a specific num%er of %lank spaces depth times %efore each

    element is printed. hen the root is to %e printed depth is 8 and no %lanks are printed.

      $uli& %#id $rintide-as() '

      $rintide-as(r##t @)

      ,

      $ri%ate %#id $rintide-as(!ree"#de t int de$th) '

      if (t >= null) '

      $rintide-as(tright de$th + 1)

      f#r (int A = 1 A B= de$th A++)

      ste#ut$rint(. .)

      ste#ut$rintln(tdata)  $rintide-as(tleft de$th + 1)

      ,

      ,

    Self-Check 

    //C1 rite out the values of each node of this tree as the tree is traversed %oth

    a. in;rder %. preorder c. post;rder 

    //C $mplement the private helper method $#st6rderPrint that will print all elements separated %y a

    space when this pu%lic method is called+

      $uli& %#id $#st6rderPrint() '

      $#st6rderPrint(r##t)

      ,

    236 

  • 8/19/2019 Binary Trees Complete Lesson

    15/29

    Binary Trees

    11.4 " *e+ other metho$sThis section provides a few algorithms on %inary trees, a few of which you may find useful.

    height

    The height of an empty tree is C/, the height of an empty tree is 8, and the height of a tree of si3egreater than / is the longer path in either the left su%tree or right su%tree from the root. The method

    considers the %ase case first to return C/ if the tree is empty. hen there is one node, height returns

    / H the maximum height of the left or right trees. !ince %oth are empty, 4athax returns C/ and the

    final result is (/ H C/) or 8.

      $uli& int height() '

      return height(r##t)

      ,

      $ri%ate int height(!ree"#de t) '

      if (t == null)

      return 1

      else

      return 1 + 4athax(height(tleft) height(tright))

      ,

    &or larger trees, height returns the larger of the height of the left su%tree or the height of the

    right su%tree.

    lea*s

    Traversal algorithms allow all nodes in a %inary tree to %e visited. !o the same pattern can %e used tosearch for elements, send messages to all elements, or count the num%er of nodes. $n these situations,

    the entire %inary tree will %e traversed.

    The following methods return the num%er of leafs in a tree hen a leaf is found, the method

    returns / H all leafs to the left H all leafs to the right. $f t references an internal node (not a leaf), therecursive calls to the left and right must still %e made to search further down the tree for leafs.

      $uli& int leafs() '

      return leafs(r##t)

      ,

      $ri%ate int leafs(!ree"#de t) '

      if (t == null)

      return @

      else '

      int result = @

      if (tleft == null DD tright == null)

      result = 1

      return result + leafs(tleft) + leafs(tright)

      ,  ,

    237 

  • 8/19/2019 Binary Trees Complete Lesson

    16/29

     Chapter 11

    *in$0in

    The find4in method returns the string that precedes all others alpha%etically. $t uses a preorder 

    traversal to visit the root nodes first (find4in could also use %e a postorder or inorder traversal). This

    example show that it may %e easier to understand or implement a %inary tree algorithm that has an

    instance varia%le initiali3ed in the pu%lic method and adGusted in the private helper method.

      $ri%ate tring in

      $uli& tring find4in() '

      if (r##t == null)

      return null

      else '

      in = r##tdata

      find4in7el$er(r##t)

      return in

      ,

      ,

      $uli& %#id find4in7el$er(!ree"#de t) '  if (t >= null) '

      tring te$ = tdata

      if (te$$are!#(in) B @)

      in = te$

      find4in7el$er(tleft)

    find4in7el$er(tright)

      ,

      , 

    Self-Check 

    //C- To inar!ree6ftrings, add method find4ax that returns the string that follows all others

    alpha%etically.

    //C To inar!ree6ftrings, add method si8e that returns the num%er of nodes in the tree.

    //C: To inar!ree6ftrings, add method t#tring that returns all elements inorder.

    //C6 To inar!ree6ftrings, add method method is;ull that returns true if the %inary tree is

    full or false if it is not. A full tree is a %inary tree in which each node has exactly 3ero or two

    children.

    238 

  • 8/19/2019 Binary Trees Complete Lesson

    17/29

    Binary Trees

    11.! Binary Search TreesA inary !earch Tree is a %inary tree with an ordering property that allows ;(log n) retrieval,

    insertion, and removal of individual elements. 5efined recursively, a %inary search tree is

    • an empty tree, or 

    • consists of a node called the root, and two children, left and right, each of which are themselves

     %inary search trees. Each node contains data at the root that is greater than all values in the left

    su%tree while also %eing less than all values in the right su%tree. 2o two nodes compare equally.

    This is called the %inary search tree ordering property.

    The following two trees represent a %inary search tree and a %inary tree respectively. oth have the

    same structure D every node has two children (which may %e empty trees shown with /). ;nly the

    first tree has the %inary search ordering property. The second does not have the !T ordering property.

    The node containing -- is found in the left su%tree of -8 instead of the right su%tree.

     " Binary Search Tree

    r##t

    2!

    -12

    /!

    !0

    603 !/

    1!2

     " Binary Tree that $oes not ha&e the or$ering property 7!! in +rong place8

    r##t

    2!

    -12

    /!

    !0

    6055 !/

    1!2

    239

     2otless

    than -8 

  • 8/19/2019 Binary Trees Complete Lesson

    18/29

     Chapter 11

    The inarear&h!ree class will add the following methods+

    insert Add an element to the %inary search tree while maintaining the ordering property.

    find eturn a reference to the element that equals the argument according to $are!#

    re#%e emove the that equals while maintaining the ordering property (left as an exercise)

    "ava generics will make this collection class more type safe. $t would %e tempting to use this familiar class heading.

    $uli& &lass inarear&h!reeBEF

  • 8/19/2019 Binary Trees Complete Lesson

    19/29

    Binary Trees

    a&untC#lle&ti#ninsert(ne- an0&unt(.4ar. 5@@@))

    a&untC#lle&ti#ninsert(ne- an0&unt(.Heff. 1@@@@))

    a&untC#lle&ti#ninsert(ne- an0&unt(."athan. 15@@@))

     

    // "eed t# &reate a du #Ae&t that -ill .euals. the a&unt in the !

    an0&unt t#e4at&hed = ne- an0&unt(.Heff. JJJ)

    an0&unt &urrentReferen&e = a&untC#lle&ti#nind (t#e4at&hed)

    assert"#t"ull(&urrentReferen&e)

    assertEuals(.Heff. &urrentReferen&egetIK())

     

    a&untC#lle&ti#n print!ide"a#s()

    &urrentReferen&ede$#sit(123:5)

     

    ste#ut$rintln(.0fter a de$#sit f#r Heff.)

    a&untC#lle&ti#n$rintide-as()

    Outut !"otice that the element with #$ %eff changes&:

      "athan 15@@@

    4ar 5@@@

      Heff 1@@@@

    0fter a de$#sit f#r Heff

      "athan 15@@@4ar 5@@@

      Heff 223:5

    ine$ #mplementation o* a BSTThe linked implementation of a %inary search tree presented here uses a private inner class !ree"#de

    that stores the type E specified as the type parameter. This means the nodes can only store the type of 

    element passed as the type argument at construction (which must implement C#$arale  or an

    interface that extends interface C#$arale).

    $uli& &lass inarear&h!reeBE extends C#$araleBEFF '

      $ri%ate &lass !ree"#de '

      $ri%ate E data  $ri%ate !ree"#de left

      $ri%ate !ree"#de right

      !ree"#de(E theKata) '

      data = theKata

      left = null

      right = null

      ,

      ,

    $ri%ate !ree"#de r##t

      $uli& inarear&h!ree() '

      r##t = null

      ,  // !he insert and find eth#ds -ill e added here

    241

  • 8/19/2019 Binary Trees Complete Lesson

    20/29

     Chapter 11

    ,

    insert

    A new node will always %e inserted as a leaf. The insert algorithm %egins at the root and proceeds as if 

    it were searching for that element. &or example, to insert a new Integer o%Gect with the value of 06

    into the following %inary search tree, 06 will first %e compared to -8. !ince 06 is less than the rootvalue of -8, the search proceeds down the left su%tree. !ince 06 is greater than 0-, the search proceeds

    to the right su%tree. !ince 06 is less than 1, the search attempts to proceed left, %ut stops. The tree to

    the left is empty. At this point, the new element should %e added to the tree as the left child of the node

    with 1.

    r##t

    2!

    -12

    /!

    !0

    603 !/

    1!2

    $re%

    28

    The search to find the insertion point ends under either of these two conditions+

    /. A node matching the new value is found.

    0. There is no further place to search. The node can then %e added as a leaf.

    $n the first case, the insert method could simply quit without adding the new node (recall that %inary

    search trees do not allow duplicate elements). $f the search stopped due to finding an empty tree, then

    a new !ree"#de with the integer 06 gets constructed and the reference to this new node replaces oneof the empty trees (the null value) in the leaf last visited. $n this case, the reference to the new node

    with 06 replaces the empty tree to the left of 1.;ne pro%lem to %e resolved is that a reference varia%le (named &urr in the code %elow) used to

    find the insertion point eventually %ecomes null. The algorithm must determine where it should store

    the reference to the new node. $t will %e in either the left link or the right link of the node last visited.

    $n other words, after the insertion spot is found in the loop, the code must determine if the new

    element is greater than or less than its soon to %e parent.

    Therefore, two reference varia%les will %e used to search through the %inary search tree. The

    !ree"#de reference named $re% will keep track of the previous node visited. (2ote+ There are other 

    ways to implement this).The following method is one solution to insertion. $t utili3es the inary !earch Tree ordering

     property. The algorithm checks that the element a%out to %e inserted is either less than or greater thaneach node visited. This allows the appropriate path to %e taken. $t ensures that the new element will %e

    242 

  • 8/19/2019 Binary Trees Complete Lesson

    21/29

    Binary Trees

    inserted into a location that keeps the tree a %inary search tree. $f the new element to %e inserted

    compares equally to the o%Gect in a node, the insert is a%andoned with a return statement.

    $uli& ##lean insert(E ne-Eleent) '

      // ne-Eleent -ill e added and this -ill still e a

      // inarear&h!ree !his tree -ill n#t insert ne-Eleent

      // if it -ill $are!# an existing eleent euall

      if (r##t == null)  r##t = ne- !ree"#de(ne-Eleent)

      else '

    // find the $r#$er leaf t# atta&h t#

      !ree"#de &urr = r##t

      !ree"#de $re% = r##t

      -hile (&urr >= null) '

      $re% = &urr

      if (ne-Eleent$are!#(&urrdata) B @)

      &urr = &urrleft

      else if (ne-Eleent$are!#(&urrdata) F @)

      &urr = &urrright

      else '

      ste#ut$rintln(ne-Eleent + . in this !.)

      return false  ,

      ,

      // C#rre&t leaf has n#- een f#und Keterine -hether t#

      // lin the ne- n#de &ae fr# $re%left #r $re%right

      if (ne-Eleent$are!#($re%data) B @)

      $re%left = ne- !ree"#de(ne-Eleent)

      else

      $re%right = ne- !ree"#de(ne-Eleent)

      ,

      return true

      , // end insert

    hen &urr finally %ecomes null, it must %e from either $re%*s left or right.

    $%

    &'

    I pre(

    This situation is handled %y the code at the end of insert that compares ne-Eleent to $re%data.

    ind  

    This inarear&h!ree needed some way to insert elements %efore find could %e tested so insertcould %e tested, a %it of illogicality. oth will %e tested now with a unit test that %egins %y inserting a

    243

  • 8/19/2019 Binary Trees Complete Lesson

    22/29

     Chapter 11

    small set of integer elements. The $rintide-as message ensures the structure of the tree has the

    !T ordering property.

    i$#rt stati& #rgAunit0ssert*

    i$#rt #rgAunitef#re

    i$#rt #rgAunit!est

    $uli& &lass inarear&h!ree!est '

      $ri%ate inarear&h!reeBIntegerF a!

      // Initiali8e a! ef#re ea&h test eth#d

    Mef#re

      $uli& stati& %#id setN$!() '

      a! = ne- inarear&h!reeBIntegerF()

      a!insert(5@)

      a!insert(25)

      a!insert(O5)

      a!insert(12)

      a!insert(39)

      a!insert(5O)

      a!insert(J@)

      a!insert(52)

      a!insert(91)

      a!$rintide-as()

      ,

      // 0n M!est in this unit test &an use a! -ith the sae J integers

      // sh#-n in Mef#re as seN$! -ill e &alled ef#re ea&h M!est

    ,

    Outut Picture the state of aBST  

      J@

      O5

      91  5O

      52

    5@

      39

      25

      12

    r##t

    2!

    -12

    !

    !0

    603 !

    1!2

    The first test method ensures that elements that can %e added result in true and those that can*t result in

    false. ?rogrammers could use this to ensure the element was added or the element already existed.

    244

  • 8/19/2019 Binary Trees Complete Lesson

    23/29

    Binary Trees

      M!est

      $uli& %#id testInsertK#es"#t0ddExistingEleents() '

      assert!rue(a!insert(OJ))

      assert!rue(a!insert(OJ))

      assert;alse(a!insert(5@))

      assert;alse(a!insert(91))

      ,

    This test method ensures that the integers are found and that the correct value is returned.

    M!est

      $uli& %#id test;indQhenInserted() '

      assertEuals(5@ a!find(5@))

      assertEuals(25 a!find(25))

      assertEuals(O5 a!find(O5))

      assertEuals(12 a!find(12))

      assertEuals(39 a!find(39))

      assertEuals(5O a!find(5O))

      assertEuals(J@ a!find(J@))

      assertEuals(52 a!find(52))

      assertEuals(91 a!find(91))

      ,

    This test method ensures that a few integers not inserted are also not found.

      M!est

      $uli& %#id test;indQhenEleents"#tInserted() '

      assert"ull(a!find(JJJ))

      assert"ull(a!find(@))

      assert"ull(a!find(JJJ))

      ,

    The search through the nodes of a a! %egins at the root of the tree. &or example, to search for a

    node that will $are!# -: equally, the method first compares -: to the root element, which has the

    value of -8. !ince -: is greater than -8, the search proceeds down the right su%tree (recall that nodes

    to the right are greater). Then -: is compared to :-. !ince -: is less than :-, the search proceeds down

    the left   su%tree of :-. Then -: is compared to the node with -:. !ince these compare equally, areference to the element is returned to the caller. The %inary search continues until one of these two

    events occur+

    /. The element is found

    0. There is an attempt to search an empty tree (nowhere to go CC the node is not in the tree)

    $n the first case, the reference to the data in the node is returned to the sender. $n the second case, the

    method returns null to indicate that the element was not in the tree.

  • 8/19/2019 Binary Trees Complete Lesson

    24/29

     Chapter 11

      // egin the sear&h at the r##t

      !ree"#de ref = r##t

     

    // ear&h until f#und #r null is rea&hed

      -hile (ref >= null) '

      if (sear&hEleent$are!#(refdata) == @)

      return refdata // f#und

      else if (sear&hEleent$are!#(refdata) B @)

      ref = refleft // g# d#-n the left sutree

      else

      ref = refright // g# d#-n the right sutree

      ,

      // ;#und an e$t tree ear&hEleent -as n#t f#und

      return null

      ,

    The following picture shows the changing values of the external reference t as it references the three

    different nodes in its search for -:+

    r##t

    2!

    -12

    /!

    !0

    603 !/

    1!2

    t

    ;ne of the reasons that %inary search trees are frequently used to store collections is the speed at

    which elements can %e found. $n a manner similar to a %inary search algorithm, half of the elements

    can %e eliminated from the search in a !T at each loop iteration. hen you go left from one node,you ignore all the elements to the right, which is usually a%out half of the remaining nodes. Assuming

    the inarear&h!ree  is fairly complete, searching in a %inary search tree is ;(log n). &or 

    example, in the previous search, t referred to only three nodes in a collection of si3e =. A tree with /8

    levels could have a maximum si3e of /,80 nodes. $t could take as few as /8 comparisons to find

    something on level /8.

    remo(e 

    The re#%e method is left as a programming exercise.

    246 

  • 8/19/2019 Binary Trees Complete Lesson

    25/29

    Binary Trees

    6. "re Trees are Goo$ or Ba$9Juch of the motivation for the design of trees comes from the fact that they support algorithms that

    are more efficient than an array or linearly linked structure. $t makes sense that the %asic operations on

    a %inary search tree should require ;(log n) time where n is the num%er of elements of the tree. e

    know that the height of a %alanced %inary tree is roughly )(log0  n

     where n is the num%er elementsin the tree. $n this case, the cost to find the element should %e on the order of ;(log n). 7 trees, Ctrees, that try to solve this pro%lem. They would do this %y reC

     %alancing the tree after operations that un%alance it are performed on them.This seems inefficient, especially when we have gone to great lengths to implement a %inary tree

    in order to make the code efficient. eC%alancing a %inary tree is a very tedious task and is %eyond the

    scope of this %ook.

  • 8/19/2019 Binary Trees Complete Lesson

    26/29

     Chapter 11

    5rogramming 5ro:ects

    11" mae0irror 

    earrange the elements of the inaryTree;f!trings class shown in this chapter to its mirroredimage. &irst get the file that is availa%le on this text%ook*s we%site.

    # BinaryTree*Strings.:a&a

    Traversal algorithms have %een shown to %egin at the root, go down the tree, and use previous

    activation records that have references to previously visited nodes. $mplement method ae4irr#r

    so it goes to the %ottom nodes first and then swaps the left and right links. Then use references from

     previous activation records to perform a swap on previously visited nodes. The following code should

    generate the output shown using inar!ree6ftrings. $t is the hardC#ded!ree in its original form

    followed %y its mirror image.

    inar!ree6ftrings t = ne- inar!ree6ftrings()

    thardC#de0!ree()

    t$rintide-as()

    t ma)e*irror()

    t$rintide-as()

    Outut 

     

    C

      <

      ;

      R

      !

       

      !

      R

      ;

      <

    C

     

    248 

  • 8/19/2019 Binary Trees Complete Lesson

    27/29

    Binary Trees

    11B "$$ 3 0etho$s to BinarySearchTree

    Add the following three methods to inarear&h!ree shown in this chapter. &irst get the file

    that is availa%le on this text%ook*s we%site.

    # BinarySearchTree.:a&a

    // Return the nuer #f n#des at an gi%en le%el

    $uli& int atKe$th(int le%el)

    // Return true if e%er le%el has the axiu nuer #f n#des

    // 6ther-ise return false

    $uli& ##lean axed6ut() 

    // Re#%e the n#de -ith eleent!#Re#%e and return true

    // #r return false if the arguent in n#t in the !

    $uli& ##lean re#%e (E eleent!#Re#%e) 

    Details

    at+epth  An empty tree has 8 nodes at all levels KL 8. A tree with one node has / node atlevel / and 8 at all other levels K 8. The following tree has two nodes at level /, three nodes at

    level 0, and one node at level 1.

      4/

    R

    / /

    < P

      Q

     maxed,-t eturns true if the inarear&h!ree has exactly the maximum num%er of nodes at

    every level in the tree. The following trees have all levels with the maximum num%er of nodes+

      4 e$t!ree 4 4  / /

      R R

    / /

    < P Q

    These %inary trees do not have the maximum num%er of elements at all levels+

      4 4 4 4

      / / /

      R R R R

    / / /

    < C < < Q

      /  

    0

    249

  • 8/19/2019 Binary Trees Complete Lesson

    28/29

     Chapter 11

    remo(e  4se the following algorithm to remove node from a !T or another algorithm that you

    derive. ou should %uild up a unit test as you test for all four cases given in the algorithm %elow from

    the simplest (#ase /) to the most difficult (#ase when curr has a left child). The method must havethis exact method heading+

    $ri%ate ##lean re#%e(E eleent!#Re#%e) '

    %emove "lgorithm

      Traverse the tree t until eleent!#Re#%e is found. 4se curr and prev to find the element

      leaving curr referring the node you want to remove. $t may %e the case that curr is null indicating

      that eleent!#Re#%e was not found. There are four cases to consider +

      #ase /+ 2ot found

      return result (false)

      #ase 0+ The root is to %e removed, %ut it has no left child.

      root L root*s right su%tree (assuming root refers the the root node in your !T)

      #ase 1+ The node is further down tree with no left child. 2ow must adGust one of the parent*s links

      if curr is on the left side of prev,

      move parent*s left link down to down to curr*s right child

      else

      curr is on the right side of prev, so move parent*s right down to down to curr*s right child

      #ase + curr has a left child.

    e can no longer ignore the left su%tree. !o find the maximum key in the left su%tree and

    move that key'value pair to the node referenced %y curr. Then eliminate the maximum in the

    left su%tree, which is now %eing referenced from the original node to remove.

    250 

  • 8/19/2019 Binary Trees Complete Lesson

    29/29