Upload
laurel-crawford
View
217
Download
2
Embed Size (px)
Citation preview
CSC 205 Java Programming II
Lecture 25
Binary Tree
Tree
A tree has a nonlinear structure Represents a
hierarchy Items in a tree do
not form a simple sequence
Allows improved efficiency for retrieving items
A Sample XML File
<?xml version="1.0"?><items> <item> <product> <description>Ink Jet Refill Kit</description> <price>29.95</price> </product> <quantity>8</quantity> </item> <item> <product> <description>4-port Mini Hub</description> <price>19.95</price> </product> <quantity>4</quantity> </item></items>
Sample: A DOM Tree
<items>
<item>
<product> <quantity>
<name> <price>
Ink JetRefill Kit
29.95
8
<item>
<product> <quantity>
<name> <price>
4-PortMini Hub
19.95
4
Basic Concepts
Related concepts Node
• Root• Leaf
Edge and path Descendant & Ancestor Parent & child nodes Sibling Sub-tree
• Left/right subtree
Binary Trees
In a binary tree, each node has up to two child nodes Height (or depth) Depth (or level) of a node
fullcomplete
0 … … …
1 … …
2 …
Level
Example – Binary Decision Tree
Binary decision tree Going down the tree with simple test
• Also known as binary taxonomy tree • Storing certain kind of knowledge
Are you a mammal?
Are you bigger than a cat Do you live underwater?
Kangaroo Mouse Trout Robin
Yes
Yes Yes
No
NoNo
Tree Representation
You would think of reference-based impl. Since we discussed nodes and edges That is definitely an option
If the tree is complete We can also use a simple array-based
implementation Using an array is always the simplest
alternative
Array-Based Representation
– for complete treesA
L G
O R I T
H M S
L G
LL GA O R I T H M S
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
Using Array Representation
The data from the root always in the [0] component of the array
For any non-root node stored in component [i], its parent is always at location [(i-1)/2] (using integer division)
For any non-leaf node stored in component [i], its left and right child nodes are always at location [2*i+1] and [2*i+2], respectively
Array-Based Representation– for any trees
With three arrays used in parallel, any binary tree can be represented One array (of Objects) to store the items Two arrays of integers to keep track of the
left and right child nodes, respectively. (hierarchical relationship)
• -1 if no child exists
See Fig 10-10 on page 436 in your text
Reference-Based Repres’n
Needs a BTNode class UML class diagram
BTNode
-item:Object-left:BTNode-right:BTNode
+BTNode (item:Object)+BTNode (item:Object,left:BTNode, right:BTNode)+setLeft(left:BTNode)+getLeft():BTNode+isLeaf():boolean
Example – Animal Guess
Are you a mammal?
Are you bigger than a cat Do you live underwater?
Kangaroo Mouse Trout Robin
Yes
Yes Yes
No
NoNo
root