chapter+18 binarytrees - university of arizonamercer/presentations/18-binarytrees.pdf · 18#2 a3 rd...
TRANSCRIPT
18-1
Chapter 18
Binary TreesData Structures and Design in Java
© Rick Mercer
18-2
A 3rd major way to structure data
w We have considered two data structures for implementing collection classes— Contiguous arrays— Singly- and Doubly-Linked structures
w Both are linear— each element has one successor and one predecessor
w Now consider a hierarchical data structure— each node may have two or more successors,
each of which which may have two or more successors
18-3
HTML pages sent to you as a treewDocument Object Model (DOM) implementation
— HTML elements sent as a standard DOM tree— Allows many browsers to render the HTML elements— We can get, change, add, or delete HTML elements
18-4
Trees are used in many wayswHierarchical file systems
— In Windows, \ represents an edge or / in Unix— Each directory may be empty, have children, some of which may be other directories
. . . . . . . . . . . .
/
bin
test sleep
etc .Spotlight-V100
sync nanorc mail.rc
18-5
package dir;
import java.io.File;
public class Dir
public static void main(String[] args) showAllFrom("/Users/mercer/Documents/Eclipseworkspaces" +
"/227Workspace/ExpressionTree");
private static void showAllFrom(String path) File folder = new File(path);File[] listOfFiles = folder.listFiles();if (listOfFiles == null)return;
for (int i = 0; i < listOfFiles.length; i++) if (!listOfFiles[i].isHidden() && listOfFiles[i].isFile()) System.out.println(" " + listOfFiles[i].getName());
else if (listOfFiles[i].isDirectory()) System.out.println(listOfFiles[i].getName() + ":");showAllFrom(listOfFiles[i].getPath());
18-6
Mac Finder: Dir.java output: .settings:
org.eclipse.jdt.core.prefs0.txt1.txt5.txt7.txt
bin:dir:
Dir.classdone:
ExpressionTree$TreeNode.classExpressionTree.classExpressionTreeTest.class
start:ExpressionTree$TreeNode.classExpressionTree.classExpressionTreeTest.classet7
src:dir:
Dir.javadone:
ExpressionTree.javaExpressionTreeTest.java
start:ExpressionTree.javaExpressionTreeTest.java
18-7
Huffman Tree we will be implementing laterw Binary trees were used in a famous first file compression algorithm
w David Huffman 1952
w Each character is stored in a leafw Follow the paths
— 0 go left, 1 go right— a is 01, e is 11— What is t?— What is…
0100011100100010111001000111111— 31 bits vs. 12*8 = 96 bits— Used JPEG, MP3, HD TV compression
'a'
't'
' ' 'e'
'h' 'r'
root
18-8
Some Tree Data Structure Uses
wCell phone T9, type jw Java’s TreeSet implementationwCompilers
— Symbol Tree, Abstract Syntax Tree wData base implementation
— IBM’s IMS for examplew A tree used to be our Arizona CS logo
18-9
Terminology
node an object containing a data reference and left & right treesroot an external reference to the root node (or null if empty)leaf a node that has no childrenbranch any internal node;; neither the root node nor a leafparent a node that refers to this onechild a node that this node refers tosibling a node with a common parentsubtree the smaller tree of nodes on either
the left or right of the current nodeheight length of the longest path from the
root to any node (empty tree -1)level or depth: length of the path
from a root to a given node76
32
1
54
rootheight = 3
level 1
level 2
level 3
18-10
The Binary Tree we will be implementingw Each TreeNode will store
— a reference to a “left” TreeNode— a reference to the element (in this case, Strings)— and a reference to a “right” TreeNode
root: an external reference like first we use in linked data structures
"T"
"R""L"
root
edges
nodes
18-11
Binary Trees
w A binary tree is a tree where all nodes have zero, one, or two children
w Each node is a leaf (no children), has a right child, has a left child, or both a left and right child
1
32
54
6
root
18-12
Recursive Definition•A binary tree is either:– empty (null), or– a root node that contains:
• data, a left tree, and a right tree
root
1
root
2
1
root
7
3
1
root
3
1
root
18-13
Expression Trees we will begin today
wCompilers build binary trees to represent expressions at runtime (no parens)
-
1+
3 *
With the infix expression ((3+(7*2))-1)
• Each parenthesized expression is represented by a tree
• Each operand is a leaf • each operator is an internal node
7 2
18-14
Evaluating Expression Trees
w To evaluate the expression tree:— Apply the parent's operator to its left and right subtrees
-
1+
3 *
7 2
14
18-15
Evaluating Expression Trees
w To evaluate the expression tree:— Apply the parent's operator to its left and right subtrees
-
1+
3 *
7 2
17
18-16
Evaluating Expression Trees
w To evaluate the expression tree:— Apply the parent's operator to its left and right subtrees
-
1+
3 *
7 2
16
18-17
Traversing Trees
-
1+
3 *
7 2
Preview three tree traversals• Inorder 3 + 7 * 2 - 1
• PostOrder 3 7 2 * + 1 -
• Preorder - + 3 * 7 2 1
w Recursive backtracking allow us to “visit” nodes
18-18
Implementing a Binary Tree
wUse an inner class again to store nodes TreeNodewNeed a reference to the element wNeed 2 references to the 2 children: left and righte
— the left and right subtrees, both of type TreeNode— could be null to indicate an empty tree
root = new TreeNode("*");
"*"
root
18-19
Add 2 More Binary Trees
root.left = new TreeNode("2");
root.right = new TreeNode("5");
"*"
root
"2" "5"
18-20
Code Demo: Hard code a treepublic class ExpressionTree
private class TreeNode private String data;private TreeNode left;private TreeNode right;
public TreeNode(String theData) data = theData;left = null;right = null;
public TreeNode(TreeNode lefTree, String theData, TreeNode righTree) left = lefTree;data = theData;right = righTree;
// end class TreeNode
// The external reference starting pointprivate TreeNode root;
public ExpressionTree() root = null;
private void hardCodeThisTree() // root -> *// / \// + 3// / \// 5 4
18-21
Tree Traversals
wTracing the elements in a tree— Can’t go from first to last— Need to go up and down the levels— Recursion helps keep track with backtracking
18-22
InOrder Tree Traversal
wVisit the left binary tree of each root before visiting the root, then visit the right
inOrder(root)
inOrder (TreeNode t) if the tree is not empty
inOrderTraverse(left Child) visit the root inOrderTraverse(right Child)
-
1+
3 *
7 2