Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.

Slides:



Advertisements
Similar presentations
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Advertisements

TREES Chapter 6. Trees - Introduction  All previous data organizations we've studied are linear—each element can have only one predecessor and successor.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Trees Chapter 8.
ITEC200 – Week08 Trees. 2 Chapter Objectives Students can: Describe the Tree abstract data type and use tree terminology such as.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Trees CMSC 433 Chapter 8.1 Nelson Padua-Perez Bill Pugh.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Fundamentals of Python: From First Programs Through Data Structures
Marc Smith and Jim Ten Eyck
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Trees. Tree Terminology Chapter 8: Trees 2 A tree consists of a collection of elements or nodes, with each node linked to its successors The node at the.
TREES Chapter 6. Trees - Introduction  All previous data organizations we've studied are linear—each element can have only one predecessor and successor.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
TREES Chapter 6 Common final examinations When: Thursday, 12/12, 3:30-5:30 PM Where: Ritter Hall - Walk Auditorium 131.
TREES Chapter 6. Chapter Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion.
TREES Chapter 6. Chapter Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion.
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Chapter 19 Implementing Trees and Priority Queues Fundamentals of Java.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Chapter 19 Implementing Trees and Priority Queues Fundamentals of Java.
CMSC 341 Introduction to Trees. 8/3/2007 UMBC CMSC 341 TreeIntro 2 Tree ADT Tree definition  A tree is a set of nodes which may be empty  If not empty,
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Binary Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Starting at Binary Trees
Trees CS 105. L9: Trees Slide 2 Definition The Tree Data Structure stores objects (nodes) hierarchically nodes have parent-child relationships operations.
CS-2852 Data Structures LECTURE 11 Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
Trees By P.Naga Srinivasu M.tech,(MBA). Basic Tree Concepts A tree consists of finite set of elements, called nodes, and a finite set of directed lines.
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 16: Trees Announcements 1.Programming project.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.
24 January Trees CSE 2011 Winter Trees Linear access time of linked lists is prohibitive  Does there exist any simple data structure for.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
18-1 Chapter 18 Binary Trees Data Structures and Design in Java © Rick Mercer.
1 CMSC 341 Introduction to Trees Textbook sections:
What is a Tree? Formally, we define a tree T as a set of nodes storing elements such that the nodes have a parent-child relationship, that satisfies the.
TREES From root to leaf. Trees  A tree is a non-linear collection  The elements are in a hierarchical arrangement  The elements are not accessible.
Trees Chapter 15.
Data Structures and Design in Java © Rick Mercer
Week 6 - Wednesday CS221.
Csc 2720 Instructor: Zhuojun Duan
Section 8.1 Trees.
Trees.
Data Structures & Algorithm Design
Binary Trees, Binary Search Trees
8.1 Tree Terminology and Applications
Trees Chapter 6.
8.2 Tree Traversals Chapter 8 - Trees.
Find in a linked list? first last 7  4  3  8 NULL
Trees.
Trees Chapter 6.
Binary Trees, Binary Search Trees
BINARY TREE CSC248 – Data Structure.
Chapter 20: Binary Trees.
Trees.
Binary Trees, Binary Search Trees
8.2 Tree Traversals Chapter 8 - Trees.
Presentation transcript:

Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees  To understand the different ways of traversing a tree  To understand the difference between binary trees, binary search trees, and heaps CS340 1

Trees - Introduction CS340  Data organizations  Linear: one predecessor or successor  Nonlinear: multiple predecessors, successors  Accessing all elements in a linear sequence is O(n)  Trees are nonlinear and hierarchical  Tree nodes can have multiple successors (but only one predecessor) 2

Trees - Introduction (cont.) CS340  Trees can represent :  class hierarchy  disk directory and subdirectories  family tree  Trees are recursive data structures  Many methods to process trees are written recursively 3

Binary trees CS340  Each element has two successors  Binary trees can be represented by arrays and linked data structures  Searching in a binary search tree generally more efficient than searching in an ordered list 4

Tree Terminology and Applications CS340

Tree Terminology CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors 6

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors The node at the top of a tree is called its root 7

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors The links from a node to its successors are called branches 8

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors The successors of a node are called its children 9

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors The predecessor of a node is called its parent Each node in a tree has exactly one parent except for the root node, which has no parent 10

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors Nodes that have the same parent are siblings 11

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors A node that has no children is called a leaf node Leaf nodes also are known as external nodes, and nonleaf nodes are known as internal nodes 12

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors A generalization of the parent-child relationship is the ancestor-descendant relationship 13

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors A subtree of a node is a tree whose root is a child of that node 14

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors The level of a node is a measure of its distance from the root plus 1 Level 1 Level 2 Level 3 15

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors Level 1 Level 2 Level 3 The level of a node is defined recursively If node n is the root of tree T, its level is 1 If node n is not the root of tree T, its level is 1 + the level of its parent 16

Tree Terminology (cont.) CS340 wikipedia science arts mathematics A tree consists of a collection of elements or nodes, with each node linked to its successors The height of a tree is the number of nodes in the longest path from the root node to a leaf node The height of this tree is 3 17

Binary Trees  In a binary tree, each node has two subtrees  A set of nodes T is a binary tree if either of the following is true  T is empty  Its root node has two subtrees, T L and T R, such that T L and T R are binary trees (T L = left subtree; T R = right subtree) CS340 18

Expression Tree  Each node contains an operator or an operand  Operands are stored in leaf nodes  Tree structure dictates the order of operand evaluation  No parenthesis needed (x + y) * ((a + b) / c) CS340 19

Binary Search Tree  Binary search trees  All elements in the left subtree precede those in the right subtree  A formal definition: A set of nodes T is a binary search tree if either of the following is true:  T is empty  If T is not empty, its root node has two subtrees, T L and T R, such that  T L and T R are binary search trees  the values in the root node of T is greater than all values in T L and is less than all values in T R 20 encyclopedia arts science mathematics

Binary Search Tree (cont.) CS340  Does not need to be sorted  Why?  When new elements are inserted (or removed) properly, the binary search tree maintains its order  Compare to an array

Binary Search Tree (cont.) CS340  Searching a BST can be O(log n)  What is the worst case?

Recursive Algorithm for Searching a Binary Tree CS if the tree is empty 2. return null (target is not found) else if the target matches the root node's data 3. return the data stored at the root node else if the target is less than the root node's data 4. return the result of searching the left subtree of the root else 5. return the result of searching the right subtree of the root

Full, Perfect, and Complete Binary Trees  Full binary tree: all nodes have either 2 children or 0 children (the leaf nodes) CS340 24

Full, Perfect, and Complete Binary Trees (cont.)  Perfect binary tree is a full binary tree of height n with exactly 2 n – 1 nodes  Find n in this example CS340 25

Full, Perfect, and Complete Binary Trees (cont.)  Complete binary tree is a perfect binary tree through level n - 1 with some extra leaf nodes at level n (the tree height), all toward the left CS340 26

General Trees  Nodes of a general tree can have any number of subtrees CS340 27

General Trees (cont.)  A general tree can be represented using a binary tree CS340 28

Tree Traversals CS340

Tree Traversals  Walking through the tree in a prescribed order and visiting the nodes as they are encountered  Three common kinds of tree traversal  Inorder  Preorder  Postorder CS340 30

Tree Traversals (cont.)  Preorder: visit root node, traverse T L, traverse T R  Inorder: traverse T L, visit root node, traverse T R  Postorder: traverse T L, traverse T R, visit root node CS340 31

Visualizing Tree Traversals  If we keep following the tree to the left, it will trace a route known as the Euler tour CS340 32

Visualizing Tree Traversals (cont.)  A Euler tour (blue path) is a preorder traversal  The sequence in this example is a b d g e h c f i j CS340 33

Visualizing Tree Traversals (cont.)  If we record a node as we return from traversing its left subtree we get an inorder traversal  The sequence is d g b h e a i f j c CS340 34

Visualizing Tree Traversals (cont.)  If we record each node as we last encounter it, we get a postorder traversal  The sequence is g d h e b i j f c a CS340 35

Traversals of Binary Search Trees and Expression Trees  With inorder traversal nodes are visited in sequence Bob, Helen, Peter, Stacy Peter Helen Stacy Bob CS340 36

Traversals of Binary Search Trees and Expression Trees (cont.)  An inorder traversal of an expression tree results in the sequence x + y * a + b / c  Or with parentheses (x + y) * ((a + b)) / c) * * / / + + c c + + y y x x b b a a CS340 37

Traversals of Binary Search Trees and Expression Trees (cont.)  A postorder traversal x y + a b + c / *  Postfix form of the expression  Operators follow operands * * / / + + c c + + y y x x b b a a CS340 38

Traversals of Binary Search Trees and Expression Trees (cont.)  A preorder traversal * + x y / + a b c  Prefix form of the expression  Operators precede operands * * / / + + c c + + y y x x b b a a CS340 39

Implementing a BinaryTree Class CS340

Node Class  The data part is a reference to type E  A binary tree node must have links to both its left and right subtrees CS340 41

Node Class (cont.) protected static class Node implements Serializable { protected E data; protected Node left; protected Node right; public Node(E data) { this.data = data; left = null; right = null; } public String toString() { return data.toString(); } Node is declared as an inner class within BinaryTree CS340 42

Node Class (cont.) protected static class Node implements Serializable { protected E data; protected Node left; protected Node right; public Node(E data) { this.data = data; left = null; right = null; } public String toString() { return data.toString(); } Node is declared protected. This way we can use it as a superclass. CS340 43

BinaryTree Class (cont.) 44

BinaryTree Class (cont.) Assuming the tree is referenced by variable bT (type BinaryTree ) then... CS340 45

BinaryTree Class (cont.) bT.root.data references the Character object storing ' * ' CS340 46

BinaryTree Class (cont.) bT.root.left references the left subtree of the root CS340 47

BinaryTree Class (cont.) bT.root.right references the right subtree of the root CS340 48

BinaryTree Class (cont.) bT.root.right.data references the Character object storing ' / ' CS340 49

BinaryTree Class (cont.) 50

BinaryTree Class (cont.) CS340  Class heading and data field declarations: import java.io.*; public class BinaryTree implements Serializable { // Insert inner class Node here protected Node root;... }

BinaryTree Class (cont.) CS340  The Serializable interface defines no methods  It provides a marker for  ObjectOutputStream : classes can be written to a binary file  ObjectInputStream: classes can be read from a binary file

Constructors CS340  The no-parameter constructor: public BinaryTree() { root = null; }  The constructor that creates a tree with a given node at the root: protected BinaryTree(Node root) { this.root = root; }

Constructors (cont.)  The constructor that builds a tree from a data value and two trees: public BinaryTree(E data, BinaryTree leftTree, BinaryTree rightTree) { root = new Node (data); if (leftTree != null) { root.left = leftTree.root; } else { root.left = null; } if (rightTree != null) { root.right = rightTree.root; } else { root.right = null; }

getLeftSubtree and getRightSubtree Methods CS340 public BinaryTree getLeftSubtree() { if (root != null && root.left != null) { return new BinaryTree (root.left); } else { return null }  getRightSubtree method is symmetric

isLeaf Method CS340 public boolean isLeaf() { return (root.left == null && root.right == null); }

toString Method CS340  Generates a string representing a preorder traversal public String toString() { StringBuilder sb = new StringBuilder(); preOrderTraverse(root, 1, sb); return sb.toString(); }

preOrderTraverse Method private void preOrderTraverse(Node node, int depth, StringBuilder sb) { for (int i = 1; i < depth; i++) { sb.append(" "); } if (node == null) { sb.append("null\n"); } else { sb.append(node.toString()); sb.append("\n"); preOrderTraverse(node.left, depth + 1, sb); preOrderTraverse(node.right, depth + 1, sb); }

preOrderTraverse Method (cont.) CS340 * + x null y null / a null b null * * + + a a y y x x / / b b (x + y) * (a / b)

Reading a Binary Tree  If we use a Scanner to read the individual lines created by the toString and preOrderTraverse methods, we can reconstruct the tree 1. Read a line that represents information at the root 2. Remove the leading and trailing spaces using String.trim 3. if it is " null " 4. return null else 5. recursively read the left child 6. recursively read the right child 7. return a tree consisting of the root and the two children

Reading a Binary Tree (cont.) CS340 public static BinaryTree readBinaryTree(Scanner scan) { String data = scan.next(); if (data.equals("null")) { return null; } else { BinaryTree leftTree = readBinaryTree(scan); BinaryTree rightTree = readBinaryTree(scan); return new BinaryTree (data, leftTree, rightTree); }

Using ObjectOutputStream and ObjectInputStream CS340  The Java API includes the class ObjectOutputStream that will write to an external file any object that is declared to be Serializable  To declare an object Serializable, add implements Serializable to the class declaration

Using ObjectOutputStream and ObjectInputStream (cont.) CS340  To write a Serializable object to a file: try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(filename)); out.writeObject(nameOfObject); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); }  A deep copy of all the nodes of the binary tree will be written to the file

Using ObjectOutputStream and ObjectInputStream (cont.) CS340  To read a Serializable object from a file: try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename)); objectName = (objectClass)in.readObject(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); }

Using ObjectOutputStream and ObjectInputStream (cont.) CS340  Do not recompile the Java source file for a class after an object of that class has been serialized  Even if you didn't make any changes to the class, the resulting.class file associated with the serialized object will have a different class signature  When you attempt to read the object, the class signatures will not match, and you will get an exception