You are on page 1of 12

Trees

Familiar with them in computer science:


A tree node has an information part and multiple links to other tree
nodes. Binary tree most common each node has 2 links.
public class TreeNode {
omparable info!
TreeNode left! "" reference to root of left subtree
TreeNode ri#ht! "" reference to root of ri#ht subtree
$%pression trees: Binary tree used to represent an e%pression:
&
' (
a B c d
)epresents the e%pression: *a ' B+ & *c d+
,ow about the e%pression a ' *b & *c d+ " e+ & f
-hat would tree look like.
Tree tra/ersal for binary tree:
0 forms: inorder1 preorder1 postorder1 all defined recursi/ely.
2norder: tra/erse left subtree1 display root1 tra/erse ri#ht subtree
3reorder: display root1 tra/erse left subtree1 tra/erse ri#ht subtree
3ostorder: tra/erse left subtree1 tra/erse ri#ht subtree1 display root
2n 4a/a:
public static /oid inorder*+ {
inorder*root+
5
pri/ate static /oid inorder*TreeNode root+ {
if *root 67 null+ {
inorder*root.left+!
8ystem.out.println*root.info.to8trin#*++!
inorder*root.ri#ht+!
5
5
To write preorder1 or postorder1 9ust switch the se:uence of these 0
statements. Trace these 0 tra/ersals for the trees shown earlier.
8how that a postorder tra/ersal displays the postfi% strin#. 2norder
tra/ersal can display a fully parenthesi;ed infi% e%pression if we
modify it to insert parentheses:
if *root 67 N<==+ {
8ystem.out.print*>*>+!
inorder*root.left+!
8ystem.out.print*root.info.to8trin#*++!
inorder*root.ri#ht+!
8ystem.out.print*>+>+!
5
8how techni:ue for :uick #eneration of tra/ersal results.
Trace an outline of the tree:
For preorder tra/ersal1 display node contents as you pass it #oin#
down. For inorder tra/ersal1 display node contents as you pass
under it. For postorder tra/ersal1 display node contents as you pass
it #oin# up.
an ha/e #eneral trees links to multiple nodes
-ords
A B ?
Apple attic ace Bob Bill bat
The node containin# info field -ords1 has 2@ links1 one to each
letter. The nodes containin# a letter1 ha/e links to a number of
nodes containin# strin#s that represent words with that letter. The
number of links /aries.
Althou#h we study only binary trees1 this is really sufficient
because we can represent any #eneral tree usin# a binary tree in
this wayA
3oint a nodeBs left link to its first child.
3oint a nodeBs ri#ht link to its ne%t siblin#.
-ords
A B ?
Apple attic ace Bob Bill bat
The left link of -ords1 points to its first child node containin#
letter A1 the ri#ht link of A points to its siblin# *node containin#
letter B+ and so on. The left link of A points to its first child *node
containin# strin# Apple.
Binary 8earch tree
A binary tree with the followin# properties: each node is lar#er
than e/ery node in its left subtree and smaller than e/ery node in
its ri#ht subtree. To determine relati/e orderin# of nodes we
compare their inormation fields.
Binary search tree:
To build a binary search tree1 use the recursi/e al#orithm below to
insert each new token:
if root 77 null "" tree is empty
insert token in root node
else if *token 77 current nodeBs key+
update current nodeBs info
else if *token C current nodeBs key+
insert token in left subtree
else
insert token in ri#ht subtree.
hat1 ace1 hop1 #o1 fat1 9an1 kid1 car1 apple1 do#1 woman1 man
hat
ace hop
#o 9an
fat kid
car woman
apple do# man
3retty stran#e lookin# tree. 8hape of a tree depends on the order in
which entries arri/e. Need to be able to rebalance a tree if it #ets
unbalanced. -e want our trees to be bushy *filled in+ unlike this
one. Talk about this formally ne%t time. 2ntuiti/ely1 letBs rebalance
a bit as we #o alon#. For tree below1 we chan#ed
ace
#o
fat
hat
fat hop
ace #o 9an
kid
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
chan#ed:
hop
9an
kid
hat
fat 9an
ace #o hop kid
car
apple
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
hat
fat 9an
apple #o hop man
ace car kid woman
-hat do we #et when we do an inorder tra/ersal of a binary search
tree.
if *root 67 null+ {
inorder*root.left+!
display root!
inorder*root.ri#ht+
5
ace1 apple1 car1 fat1 #o1 hat1 hop1 9an1 kid1 man1 woman ( keys are
in increasin# se:uence
Tree search is an E*lo# n+ process 9ust like binary search
)ecursi/e search al#orithm:
if *root 77 null+
)eturn null
else if *rootBs key 77 tar#et+
)eturn rootBs info
else if *tar#et C rootBs key+
8earch for tar#et in left subtree
else
8earch for tar#et in ri#ht subtree
4a/a implementations:
"" 2nterface that must be implemented by a FcomparableF ob9ect
public interface omparable {
public boolean e:uals*Eb9ect o+! "" e:uality test
public boolean lessThan*Eb9ect o+! "" relational test
5
"" A tree node
public class TreeNode {
"" ?ata Fields
omparable info! "" information field
TreeNode left! "" left subtree
TreeNode ri#ht! "" ri#ht subtree
"" Gethods
"" onstructors
public TreeNode*+ {5!
public TreeNode*Eb9ect i+ {
info 7 *omparable+ i!
left 7 null!
ri#ht 7 null!
5
public 8trin# to8trin#*+ {
return info.to8trin#*+!
5
public omparable #et2nfo*+ {
return info!
5
public /oid store2nfo*Eb9ect c+ {
info 7 *omparable+ c!
5
"" 2nserts item where it belon#s in tree or updates info field
"" for an item whose key is already in the tree.
"" )eturns true if item was new.
"" )eturns false if itemBs key was already in tree.
public boolean insertNode*Eb9ect item+ {
if *info.e:uals*item++ {
return false! "" already in tree
5 else if *item.lessThan*this.info++
"" item C root key ( check left subtree
if *left 77 null+ {
left 7 new TreeNode*item+! "" 2nsert item.
return true!
5 else
return left.insertNode*item+! "" Go/e left.
"" tar#et key H root key ( check ri#ht subtree
else if *ri#ht 77 null+ {
ri#ht 7 new TreeNode*item+! "" 2nsert item.
return true!
5 else
return ri#ht.insertNode*item+! "" Go/e ri#ht.
5 "" end insertNode
5 "" end TreeNode
import my2E.'!
public class 8earchTree {
"" ?ata fields
pri/ate TreeNode root! "" root of this tree
public boolean is$mpty*+ {
return *root 77 null+!
5
"' 2nserts item into a binary search tree.
precondition : none
postcondition: )eturns true if the insertion is
performed. )eturns false if there
is a node with the same key as item.
'"
public boolean insert*Eb9ect item+ {
if *root 77 null+ { ""empty search tree
"" 2nsert item in root. Tree has I node.
root 7 new TreeNode*item+!
return true!
5 else
"" 2nsert in tree whose >root nodeA is pointed to by root.
return root.insertNode*item+! "" use TreeNode method
5
"' ?isplays a binary search tree in key order.
precondition : none
postcondition: ?isplays each node in key order.
'"
pri/ate /oid display*TreeNode root+ {
if *root 67 null+ {
display*root.left+!
2E.display)esult*Fdata is F &
root.info.to8trin#*+!
display*root.ri#ht+!
5
5
public /oid display*+ {
display*root+!
5
"" 2nsert methods search1 replace1 and delete here.
5 "" class 8earchTree
Tree ?eletion
$asy to delete a leaf node *no children+ disconnect it.
To delete a node with one child1 9ust bypass the child *connect
to the childBs left or ri#ht subtree1 whiche/er e%ists+.
To delete a node with two children1 find the smallest node in its
ri#ht subtree *or the lar#est node in its left subtree+1 copy the
minimum /alue into the info field of the >node to be deletedA
and then delete the minimum node instead.
"" part of class 8earchTree
public /oid delete *Eb9ect item+ {
root 7 delete*item1 root+!
5
public /oid delete*Eb9ect item1 TreeNode t+ {
if *t 77 null+
8ystem.out.println*Fnode is missin#F+! "" stop recursion
else if ***omparable+ item+.lessThan*t.info++
t.left 7 delete*item1 t.left+! "" recursi/e step
else if *t.info.lessThan**omparable+ item++
t.ri#ht 7 delete*item1 t.ri#ht+! "" recursi/e step
else "" item matches t.info ( see if node t has children
if *t.left 67 null JJ t.ri#ht 67 null+ {
"" node t has two children
"" replace item with the smallest /alue in ri#ht subtree
t.info 7 *omparable+ findGin*t.ri#ht+!
"" remo/e the node that pre/iously
"" contained smallest /alue
t.ri#ht 7 remo/eGin*t.ri#ht+!
5 else "" node t has I or K children
"" connect node t to sin#le child ( stop recursion
if *t.left 77 null+
t 7 t.ri#ht!
else
t 7 t.left!
return t!
5
Gethod findGin searches for the smallest element in a tree and
returns its information part. Basically keeps mo/in# left until it
reaches a node with no left child.
3seudo code
if the left subtree is empty
)eturn the info part of the root of this tree
$lse search for the minimum /alue in the left subtree and return it.
Gethod remo/eGin also searches for the smallest element in a tree
*mo/es to the left until it finds a node with no left child+. Then it
disconnects that node by connectin# the smallest nodeBs parent to
the smallest nodeBs ri#ht child. The smallest node cannot ha/e a
left child too because if it did1 its left child would be smaller than
it.
if its left subtree is empty
connect the tree root to its ri#ht subtree *t 7 L +
$lse
remo/e the minimum node from the left subtree *t.left 7 L+
)eturn t!

You might also like