Download presentation
Presentation is loading. Please wait.
Published byLaurel Crawford Modified over 9 years ago
1
CSC 205 Java Programming II Lecture 25 Binary Tree
2
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
3
A Sample XML File Ink Jet Refill Kit 29.95 8 4-port Mini Hub 19.95 4
4
Sample: A DOM Tree Ink Jet Refill Kit 29.95 8 4-Port Mini Hub 19.95 4
5
Basic Concepts Related concepts Node Root Leaf Edge and path Descendant & Ancestor Parent & child nodes Sibling Sub-tree Left/right subtree
6
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
7
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 catDo you live underwater? KangarooMouseTroutRobin Yes No
8
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
9
Array-Based Representation – for complete trees A LG ORIT HMS LG LLGAORITHMS [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
10
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
11
Array-Based Representation – for any trees With three arrays used in parallel, any binary tree can be represented One array (of Object s) 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
12
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
13
Example – Animal Guess Are you a mammal? Are you bigger than a catDo you live underwater? KangarooMouseTroutRobin Yes No root
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.