Trees Chapter 16. 2 Chapter Contents Tree Concepts Hierarchical Organizations Tree Terminology Traversals of a Tree Traversals of a Binary Tree Traversals.

Slides:



Advertisements
Similar presentations
TREES Chapter 6. Trees - Introduction  All previous data organizations we've studied are linear—each element can have only one predecessor and successor.
Advertisements

Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
A Binary Search Tree Implementation Chapter Chapter Contents Getting Started An Interface for the Binary Search Tree Duplicate Entries Beginning.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
Trees Chapter 8.
Trees Chapter Chapter Contents Tree Concepts Hierarchical Organizations Tree Terminology Traversals of a Tree Traversals of a Binary Tree Traversals.
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.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
A Binary Search Tree Implementation Chapter Chapter Contents Getting Started An Interface for the Binary Search Tree Duplicate Entries Beginning.
Trees Chapter 25 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
Transforming Infix to Postfix
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
Trees Chapter 23 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Fundamentals of Python: From First Programs Through Data Structures
Trees. 2 Tree Concepts Previous data organizations place data in linear order Some data organizations require categorizing data into groups, subgroups.
1 Trees What is a Tree? Tree terminology Why trees? General Trees and their implementation N-ary Trees N-ary Trees implementation Implementing trees Binary.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 20: Binary 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.
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 & Graphs Chapter 25 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
Chapter 19: Binary Trees. Objectives In this chapter, you will: – Learn about binary trees – Explore various binary tree traversal algorithms – Organize.
Trees Chapter 15 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
CS Data Structures Chapter 15 Trees Mehmet H Gunes
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.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 10: Trees Data Abstraction & Problem Solving with C++
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.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
Chapter 10-A Trees Modified
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.
Compiled by: Dr. Mohammad Omar Alhawarat
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.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 4. Trees.
TREES. What is a tree ? An Abstract Data Type which emulates a tree structure with a set of linked nodes The nodes within a tree are organized in a hierarchical.
Data Structures TREES.
Trees : Part 1 Section 4.1 (1) Theory and Terminology (2) Preorder, Postorder and Levelorder Traversals.
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
Trees Chapter Chapter Contents Tree Concepts Hierarchical Organizations Tree Terminology Traversals of a Tree Traversals of a Binary Tree Traversals.
Trees Chapter 23 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
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.
Chapter 10: Trees A tree is a connected simple undirected graph with no simple circuits. Properties: There is a unique simple path between any 2 of its.
Trees Ellen Walker CPSC 201 Data Structures Hiram College.
Trees and Graphs CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
Data Structures Azhar Maqsood School of Electrical Engineering and Computer Sciences (SEECS-NUST) Binary Trees.
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 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
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.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 4. Trees.
Trees Chapter 15.
CSCE 210 Data Structures and Algorithms
A Binary Search Tree Implementation
Csc 2720 Instructor: Zhuojun Duan
Section 8.1 Trees.
A Binary Search Tree Implementation
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Binary Trees, Binary Search Trees
Trees.
CSC 143 Java Trees.
B.Ramamurthy Chapter 9 CSE116A,B
Binary Trees, Binary Search Trees
Presentation transcript:

Trees Chapter 16

2 Chapter Contents Tree Concepts Hierarchical Organizations Tree Terminology Traversals of a Tree Traversals of a Binary Tree Traversals of a General Tree Java Interfaces for Trees Interfaces for All Trees Interface for Binary Examples of Binary Trees Expression Trees Decision Trees Binary Search Trees Examples of General Trees Parse Trees Game Trees

3 Tree Concepts Previous data organizations place data in linear order Some data organizations require categorizing data into groups, subgroups This is hierarchical classification Data items appear at various levels within the organization

4 Hierarchical Organization Example: File directories Computer files organized into folders.

5 Hierarchical Organization Example: A university's organization A university's administrative structure.

6 Hierarchical Organization Example: Family trees Carole's children and grandchildren.

7 Tree Terminology A tree is A set of nodes Connected by edges The edges indicate relationships among nodes Nodes arranged in levels Indicate the nodes' hierarchy Top level is a single node called the root

8 Tree Terminology A tree equivalent to the my stuff tree

9 Tree Terminology Nodes at a given level are children of nodes of previous level Node with children is the parent node of those children Nodes with same parent are siblings Node with no children is a leaf node The only node with no parent is the root node All others have one parent each

10 Tree Terminology Empty trees? Some authors specify a general tree must have at least the root node This text will allow all trees to be empty A node is reached from the root by a path The length of the path is the number of edges that compose it The height of a tree is the number of levels in the tree The subtree of a node is a tree rooted at a child of that node

11 Binary Trees General tree: in general, node can have an arbitrary number of children Binary tree if each node has at most two children Three binary trees.

12 Binary Trees A binary tree is either empty or has the following form Where T left and T right are binary trees

13 Binary Trees If a binary tree of height h has all leaves on the same level h and every nonleaf in a full binary tree has exactly two children A complete binary tree is full to its next-to-last level Leaves on last level filled from left to right

14 Binary Trees The number of nodes in a full binary tree as a function of the tree's height.

15 Binary Trees Total number of nodes n for a full tree can be calculated as: The height of a binary tree with n nodes that is either complete or full is log 2 (n + 1)

16 Traversals of a Tree Traversing items is a common operation. Previous chapters, data was arranged linearly. Order of traversal was clear. During tree traversal, we must visit each item exactly once in a systematic way. The order is not unique. Visiting a node Processing the data within a node A traversal can pass through a node without visiting it at that moment

17 Traversals of a Tree Subtree of the root of binary trees are themselves binary trees. Using this recursive nature, we define recursive traversal: For a binary tree Visit the root Visit all nodes in the root's left subtree Visit all nodes in the root's right subtree Order does not matter. Visit root before, between or after visiting two subtrees.

18 Traversals of a Tree Preorder traversal: visit root before the subtrees The visitation order of a preorder traversal.

19 Traversals of a Tree Inorder traversal: visit root between visiting the subtrees The visitation order of an inorder traversal.

20 Traversals of a Tree Postorder traversal: visit root after visiting the subtrees The visitation order of a postorder traversal. These are examples of a depth-first traversal. Follow a path that descends the levels of a tree as deeply as possible until reaches a leaf These are examples of a depth-first traversal. Follow a path that descends the levels of a tree as deeply as possible until reaches a leaf

21 Traversals of a Tree Level-order traversal: begin at the root, visit nodes one level at a time The visitation order of a level-order traversal. This is an example of a breadth-first traversal. Follow a path that explores an entire level before moving to the next level. This is an example of a breadth-first traversal. Follow a path that explores an entire level before moving to the next level.

22 Traversals Exercise The order of these nodes being visited using 4 different traversal methods

23 Answer In this binary tree, D = node, L = left, R = right Preorder (DLR) traversal yields: A, H, G, I, F, E, B, C, D Postorder (LRD) traversal yields: G, F, E, I, H, D, C, B, A In-order (LDR) traversal yields: G, H, F, I, E, A, B, D, C Level-order traversal yields: A, H, B, G, I, C, F, E, D

24 Traversals of a General Tree A general tree has traversals that are in Level order Preorder Postorder Inorder traversal not well defined for a general tree

25 Traversals of a General Tree The visitation order of two traversals of a general tree: (a) preorder; (b) postorder.

26 Java Interfaces for Trees An interface that specifies operations common to all trees public interface TreeInterface {public Object getRootData(); public int getHeight(); public int getNumberOfNodes(); public boolean isEmpty(); public void clear(); } // end TreeInterface

27 Java Interfaces for Trees Interface for iterators for various traversals import java.util.Iterator; public interface TreeIteratorInterface {public Iterator getPreorderIterator(); public Iterator getPostorderIterator(); public Iterator getInorderIterator(); public Iterator getLevelOrderIterator(); } // end TreeIteratorInterface

28 Java Interfaces for Trees Interface for a class of binary trees public interface BinaryTreeInterface extends TreeInterface, TreeIteratorInterface {/** Sets an existing binary tree to a new one-node binary tree. rootData an object that is the data in the new tree’s root */ public void setTree(Object rootData); /** Sets an existing binary tree to a new binary tree. rootData an object that is the data in the new tree’s root leftTree the left subtree of the new tree rightTree the right subtree of the new tree */ public void setTree(Object rootData,| BinaryTreeInterface leftTree, BinaryTreeInterface rightTree); } // end BinaryTreeInterface

29 Construct A Binary Tree BinaryTreeInterface fTree; fTree = new BinaryTree (); fTree.setTree(“F”); gTree = new BinaryTree (); gTree.setTree(“G”); eTree = new BinaryTree (); eTree.setTree(“E”, ftree, gTree); …..

30 Expression Trees for Algebraic Expression The root contains the binary operator and children contain the operands. Order of children matches the order of operands. Such binary tree is called expression Trees. No parentheses since order of operations is captured by the shape of the expression tree Expression trees for four algebraic expressions..

31 Expression Trees Inorder traversal produces the original infix expression, but without any parentheses Preorder traversal produces the prefix expression Postorder traversal produces the postfix expression (b) preorder: +*abc postorder: ab*c+

32 Expression Trees Algorithm for evaluating an expression tree in postorder traversal Algorithm evaluate(expressionTree) if (root of tree is operand) return operand else {firstOperand = evaluate(left subtree of expressionTree) secondOperand = evaluate(right subtree of expressionTree) operator = the root of expressionTree return the result of the operation operator and its operands firstOperand and secondOperand }

33 Exercises Draw an expression tree for each of these algebraic expressions. a. a+b*c b. (a+b)*c

34 Decision Trees Basis of Expert System An expert system also known as a knowledge based system that contains some knowledge. It was first developed by researchers in artificial intelligence. The most common form of expert systems is made up of a set of rules that analyze information. Each parent in a decision tree is a question that has a finite number of response. Each possible answer to the question corresponds to a child of the node. Leave node are conclusions that have no children

35 Decision Trees Helps users solve problems, make decisions A binary decision tree to solve TV problem.

36 Decision Trees A possible Java interface for a binary decision tree. public interface DecisionTreeInterface extends BinaryTreeInterface {/** Task: Gets the data in the current node. the data object in the current node */ public Object getCurrentData(); /** Task: Determines whether current node contains an answer. true if the current node is a leaf */ public boolean isAnswer(); /** Task: Moves the current node to the left (right) child of the current node. */ public void advanceToNo(); public void advanceToYes(); /** Task: Sets the current node to the root of the tree.*/ public void reset(); } // end DecisionTreeInterface

37 Decision Trees The decision tree for a guessing game Facts are used to build this decision tree.

38 Binary Search Trees We can traverse nodes in any tree, so searching a node is possible. The least efficient search will be sequential search. However, a search tree organizes its data so that a search is more efficient Binary search tree Nodes contain Comparable objects A node's data is greater than the data in the node's left subtree A node's data is less than the data in the node's right subtree

39 Binary Search Trees A binary search tree of names.

40 Binary Search Trees Two binary search trees containing the same names as the tree in previous slide

41 Questions How many different binary search trees can you form from the strings a, b, and c? What are the heights of the shortest and tallest trees that you formed?

42 Answer How many different binary search trees can you form from the strings a, b, and c? 5 different structures What are the heights of the shortest and tallest trees that you formed? 2 and 3

43 Binary Search Trees Search begins at the root, ends at either the target node or leaf node. The number of comparison is the number of nodes along the path from the root to target node. The height of a tree directly affects the length of the longest path from the root to a leaf and hence affects the efficiency of a worst-case search. Searching a binary search tree of height h is O(h).

44 Binary Search Trees An algorithm for searching a binary search tree Algorithm bstSearch(binarySearchTree, desiredObject) // Searches a binary search tree for a given object. // Returns true if the object is found. if (binarySearchTree is empty) return false else if (desiredObject == object in the root of binarySearchTree) return true else if (desiredObject < object in the root of binarySearchTree) return bstSearch(left subtree of binarySearchTree, desiredObject) else return bstSearch(right subtree of binarySearchTree, desiredObject)

45 Heaps A complete binary tree Nodes contain Comparable objects Each node contains no smaller (or no larger) than objects in its descendants Maxheap Object in a node is ≥ its descendant objects. Root node contains the largest data Minheap Object in a node is ≤ descendant objects Root node contains the smallest data

46 Heaps (a) A maxheap and (b) a minheap that contain the same values

47 Question? Can a binary search tree ever be a maxheap? Can you think of any ADT we have learnt so far that can be implemented by maxheap?

48 Parse Tree for Compiler These rules form a grammar for algebraic expression, much like English language grammar. An algebraic expression is either a term or two terms separated by + or – operator A term is either a factor or two factors separated by * or / operator. A factor is either a variable or an algebraic expression enclosed in parentheses. A variable is a single letter Check the syntax of each statement by applying these rules, if we can the derivation can be given as a parse tree.

49 Parse Tree A parse tree for the algebraic expression a * (b + c) 1). An algebraic expression is either a term or two terms separated by + or – operator 2). A term is either a factor or two factors separated by * or / operator. 3). A factor is either a variable or an algebraic expression enclosed in parentheses. 4). A variable is a single letter

50 Parse Tree Parse tree should be a general tree so that I can accommodate any expression. We are not restricted to algebraic expression. We can use parse tree to check the validity of any string according to any grammar Compiler uses parse tree both to check the syntax of a program and to produce executable code.

51 Exercise Draw a parse tree for the algebraic expression a*b + c a + b*c (a+b)*(c-d)

52 Answer

53 Exercise At most, how many nodes can a binary tree have at level n? Use induction to prove your answer.