Tree properties and traversals

Slides:



Advertisements
Similar presentations
Trees and Binary Trees Become Rich Force Others to be Poor Rob Banks
Advertisements

Data Structures Lecture 6 Fang Yu Department of Management Information Systems National Chengchi University Fall 2010.
Trees Briana B. Morrison Adapted from Alan Eugenio.
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.
© 2004 Goodrich, Tamassia Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery.
Trees1 Recursion Recursion is a concept of defining a method that makes a call to itself.
CS 206 Introduction to Computer Science II 09 / 22 / 2008 Instructor: Michael Eckmann.
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Chapter 7: Trees Objectives:
1 Chapter 7 Trees. 2 What is a Tree In computer science, a tree is an abstract model of a hierarchical structure A tree consists of nodes with a parent-child.
CS 206 Introduction to Computer Science II 02 / 11 / 2009 Instructor: Michael Eckmann.
© 2004 Goodrich, Tamassia Trees1 this is a tree. © 2004 Goodrich, Tamassia Trees2 What is a Tree? In computer science, a tree is an abstract model of.
Trees COMP53 Oct 31, What is a Tree? A tree is an abstract model of a hierarchical structure A tree consists of nodes with a parent-child relation.
Trees1 Part-C Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
CHAPTER 12 Trees. 2 Tree Definition A tree is a non-linear structure, consisting of nodes and links Links: The links are represented by ordered pairs.
Marc Smith and Jim Ten Eyck
Binary and Other Trees CSE, POSTECH. 2 2 Linear Lists and Trees Linear lists are useful for serially ordered data – (e 1,e 2,e 3,…,e n ) – Days of week.
Joseph Lindo Trees Sir Joseph Lindo University of the Cordilleras.
Trees CS /02/05 L7: Trees Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved Definition.
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.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
Trees.
Make Money Fast! Stock Fraud Apply shortcuts Bank Robbery Just For Laughs Trees This one is cool eITnotes.com For more notes and topics visit:
Trees CSCI 3333 Data Structures. Acknowledgement  Dr. Bun Yue  Mr. Charles Moen  Dr. Wei Ding  Ms. Krishani Abeysekera  Dr. Michael Goodrich  Dr.
Saturday, 04 Apr 2010 University of Palestine Computer Science II Trees.
Trees. What is a Tree? In computer science, a tree is an abstract model of a hierarchical structure A tree consists of nodes with a parent- child relation.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
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.
Data Structures and Algorithms Lecture (BinaryTrees) Instructor: Quratulain.
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.
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.
Recursive Data Structures and Grammars  Themes  Recursive Description of Data Structures  Grammars and Parsing  Recursive Definitions of Properties.
Lecture11: Tree I Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, §4.1 – 4.2 1Izmir University of Economics.
Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2010 Goodrich, Tamassia.
Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2013 Goodrich, Tamassia, Goldwasser.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
CH 7. TREES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
24 January Trees CSE 2011 Winter Trees Linear access time of linked lists is prohibitive  Does there exist any simple data structure for.
Trees and Graphs CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
CH 7 : TREE ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2010 Goodrich, Tamassia.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
© 2004 Goodrich, Tamassia Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery.
Chapter 7 Trees_ Part2 TREES. Depth and Height 2  Let v be a node of a tree T. The depth of v is the number of ancestors of v, excluding v itself. 
1 CMSC 341 Introduction to Trees Textbook sections:
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture13.
TREE Ahsan Ahmed College of Computer and Information Science Majma’ah University 1.
1 COMP9024: Data Structures and Algorithms Week Five: Trees Hui Wu Session 1, 2015
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 5/10/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Lecture 1 (UNIT -4) TREE SUNIL KUMAR CIT-UPES.
CMSC 341 Introduction to Trees 8/3/2007 CMSC 341 Tree Intro.
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery Trees
CMSC 341 Introduction to Trees.
Trees 9/21/2018 9:58 PM Trees this is a tree Trees.
Chapter 7. Trees & Binary Trees
Week nine-ten: Trees Trees.
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery Trees
Trees Palestine Gaza West Bank 48 Stolen Land Trees Trees
CMSC 341 Introduction to Trees CMSC 341 Tree Intro.
Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery
Binary Trees.
NATURE VIEW OF A TREE leaves branches root. NATURE VIEW OF A TREE leaves branches root.
Presentation transcript:

Tree properties and traversals Thursday February 12, 2015 Tree properties and traversals CS16: Introduction to Data Structures & Algorithms

Outline Tree ADT Binary Tree ADT Breadth-first traversal Thursday February 12, 2015 Outline Tree ADT Binary Tree ADT Breadth-first traversal Depth-first traversal Recursive DFT: pre-order, post-order, in-order Euler Tour traversal Practice problems

Thursday February 12, 2015 What is a Tree? In computer science, a tree is an abstract model of a hierarchical structure A tree consists of nodes with a parent- child relation Applications: Organization charts File systems Computers ‘R’ Us Sales R&D Manufacturing Laptops Desktops US International Europe Asia Canada

Tree Terminology subtree A B D C G H E F I J K Thursday February 12, 2015 Tree Terminology Root: node without a parent (A) Internal node: node with at least one child (A, B, C, F) External node (a.k.a. leaf ): node without children (E, I, J, K, G, H, D) Parent node: node immediately above a given node (parent of C is A) Child node: node(s) immediately below a given node (children of C are G and H) Ancestors of a node: parent, grandparent, grand- grandparent, etc. (ancestors of G are C, A) Depth of a node: number of ancestors (I has depth 3) Height of a tree: maximum depth of any node (tree with just a root has height 0, this tree has height 3) Descendant of a node: child, grandchild, grand- grandchild, etc. Subtree: tree consisting of a node and its descendants A B D C G H E F I J K subtree

Tree ADT (Abstract Data Structure) Thursday February 12, 2015 Tree ADT (Abstract Data Structure) Tree methods: int size(): returns the number of nodes boolean isEmpty(): returns true if the tree is empty Node root(): returns the root of the tree Node methods: Node parent(): returns the parent of the node Node[ ] children(): returns the children of the node boolean isInternal(): returns true if the node has children boolean isExternal(): returns true if the node is a leaf boolean isRoot(): returns true if the node is the root

Binary Tree In CS16, we’ll be looking mainly at binary trees Thursday February 12, 2015 Binary Tree In CS16, we’ll be looking mainly at binary trees A binary tree is a tree with the following property: Each internal node has at most 2 children: a left child and a right child. Even if there is only one child, the child is still specified as left or right. Recursive definition: A tree consisting of a single node, or A tree whose root has at most 2 children, each of which is a binary tree A B C F G D E H I

Thursday February 12, 2015 Binary Tree ADT In addition to the methods specified in the Tree ADT, binary tree Nodes have a few additional methods: Node left(): returns the left child of the node if there is one, otherwise null Node right(): returns the right child of the node if there is one, otherwise null boolean hasLeft(): returns true if node has a left child boolean hasRight(): returns true if node has a right child

Thursday February 12, 2015 Perfection A binary tree is a perfect binary tree if every level is completely full Not perfect Perfect!

Completeness A binary tree is a left-complete binary tree if: Thursday February 12, 2015 Completeness A binary tree is a left-complete binary tree if: every level is completely full, possibly excluding the lowest level all nodes are as far left as possible Left-complete! Not left-complete

Thursday February 12, 2015 Tree Traversals Unlike an array, it’s not always obvious how to visit every element stored in a tree A tree traversal is an algorithm for visiting every node in a tree There are many possible tree traversals that visit the nodes in different orders

Breadth-first traversal Thursday February 12, 2015 Breadth-first traversal Starting from the root node, visit both of its children first, then all of its grandchildren, then great-grandchildren etc… Also known as level-order traversal A B C F G D E H I Breadth-first Traversal: A,B,C,D,E,F,G,H,I

Breadth-first traversal (2) Thursday February 12, 2015 Breadth-first traversal (2) General strategy: use a queue to keep track of the order of nodes Pseudocode: The queue guarantees that all the nodes of a given level are visited before any of their children are visited Can enqueue node’s left and right children in any order function bft(root): //Input: root node of tree //Output: None Q = new Queue() enqueue root while Q is not empty: node = Q.dequeue() visit(node) enqueue node’s left & right children

Depth-first traversal Thursday February 12, 2015 Depth-first traversal Starting from the root node, explore each branch as far as possible before backtracking This can still produce many different orders, depending on which branch you visit first A B C F G D E H I Depth-first Traversal: A,C,G,F,B,E,I,H,D or A,B,D,E,H,I,C,F,G

Depth-first traversal (2) Thursday February 12, 2015 Depth-first traversal (2) General strategy: use a stack to keep track of the order of nodes Pseudocode: The stack guarantees that you explore a branch all the way to a leaf before exploring another Can add children to stack in any order function dft(root): //Input: root node of tree //Output: none S = new Stack() push root onto S while S is not empty: node = S.pop() visit(node) push node’s left and right children

Visualizations BFT DFT Thursday February 12, 2015 Visualizations BFT DFT BFT gif: http://en.wikipedia.org/wiki/Breadth-first_search#mediaviewer/File:Animated_BFS.gif DFT gif: https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif BFT gif: http://en.wikipedia.org/wiki/Breadth-first_search#mediaviewer/File:Animated_BFS.gif DFT gif: https://upload.wikimedia.org/wikipedia/commons/7/7f/Depth-First-Search.gif

Recursive Depth-First Traversals Thursday February 12, 2015 Recursive Depth-First Traversals We can also implement DFT recursively! Using recursion, we can end up with 3 different orders of nodes, depending on our implementation Pre-order – visits each node before visiting its left and right children Post-order – visits each node after visiting its left and right children In-order – visits the node’s left child, itself, and then its right child

Pre-order Traversal: A,B,D,E,H,I,C,F,G Thursday February 12, 2015 Pre-order traversal A B C F G D E H I function preorder(node): //Input: root node of tree //Output: None visit(node) if node has left child preorder(node.left) if node has right child preorder(node.right) Pre-order Traversal: A,B,D,E,H,I,C,F,G Note: this is similar to iterative DFT

Post-order Traversal: Thursday February 12, 2015 Post-order traversal A B C F G D E H I function postorder(node): //Input: root node of tree //Output: None if node has left child postorder(node.left) if node has right child postorder(node.right) visit(node) Post-order Traversal: D,H,I,E,B,F,G,C,A

In-order traversal function inorder(node): //Input: root node of tree Thursday February 12, 2015 In-order traversal A B C F G D E H I function inorder(node): //Input: root node of tree //Output: None if node has left child inorder(node.left) visit(node) if node has right child inorder(node.right) In-order Traversal: D,B,H,E,I,A,F,C,G

Visualizations Pre-Order In-order Post-order Think of the Thursday February 12, 2015 Visualizations Pre-Order Think of the prefix as when the root is visited! In-order Preorder gif: http://ceadserv1.nku.edu/longa//classes/mat385_resources/docs/traversal_files/PreOrderTrav.gif Inorder gif: http://ceadserv1.nku.edu/longa//classes/mat385_resources/docs/traversal_files/InorderTrav.gif Postorder gif: http://ceadserv1.nku.edu/longa//classes/mat385_resources/docs/traversal_files/PostorderTrav.gif Post-order Preorder gif: http://ceadserv1.nku.edu/longa//classes/mat385_resources/docs/traversal_files/PreOrderTrav.gif Inorder gif: http://ceadserv1.nku.edu/longa//classes/mat385_resources/docs/traversal_files/InorderTrav.gif Postorder gif: http://ceadserv1.nku.edu/longa//classes/mat385_resources/docs/traversal_files/PostorderTrav.gif

Euler Tour Traversal Generic traversal of a binary tree Thursday February 12, 2015 Euler Tour Traversal Generic traversal of a binary tree Includes as special cases the pre-order, post-order, and in-order traversals Walk around the tree and visit each node three times: On the left (pre-order) From below (in-order) On the right (post-order) Creates subtrees for all nodes L R B

Euler Traversal Pseudocode Thursday February 12, 2015 Euler Traversal Pseudocode function eulerTour(node): // Input: root node of tree // Output: None visitLeft(node) // Pre-order if node has left child: eulerTour(node.left) visitBelow(node) // In-order if node has right child: eulerTour(node.right) visitRight(node) // Post-order 1 A B C F G D E H I 27 17 2 16 18 26 22 6 3 5 25 7 15 19 21 23 4 20 24 11 8 10 12 14 9 13

Thursday February 12, 2015 Aside: Decoration Often you’ll be asked to decorate each node in a tree with some value “Decorating” a node just means associating a value to it. There are two conventional ways to do this: Add a new attribute to each node e.g. node.numDescendants = 5 Maintain a dictionary that maps each node to its decoration – do this if you don’t want to or can’t modify the original tree e.g. descendantDict[node] = 5

When do I use what traversal? Thursday February 12, 2015 When do I use what traversal? With so many tree traversals in your arsenal, how do you know which one to use? Sometimes it doesn’t matter, but often there will be one traversal that makes solving a problem much easier

Thursday February 12, 2015 Practice Problem 1 Decorate each node with the number of its descendants Best traversal: post-order It’s easy to calculate the number descendants of a node if you already know how many descendants each of its children has Since post-order traversal visits both children before the parent, this is the traversal we want Try writing some pseudocode for this!

Thursday February 12, 2015 Practice Problem 2 Given the root of a tree, determine if the tree is perfect Best traversal: breadth-first This problem is easiest solved by traversing the tree level-by-level We can keep track of the current level, and at each level count the number of nodes we see Each level should have exactly twice as many nodes as the last There are other ways to solve this problem too - can you think of any?

Thursday February 12, 2015 Practice Problem 3 Given an arithmetic expression tree, evaluate the expression Best traversal: post-order In order to evaluate an arithmetic operation, you first need to evaluate the sub-expression on each side What should you do when you get to a leaf? + - / 9 3 7 4 (7 – (4 + 3)) + (9 / 3)

Thursday February 12, 2015 Practice Problem 4 Given an arithmetic expression tree, print out the expression, without parentheses Best traversal: in-order in-order traversals gives you the nodes from left to right, which is exactly the order we want! + - / 9 3 7 4 7 – 4 + 3 + 9 / 3

Thursday February 12, 2015 Practice Problem 5 Given an arithmetic expression tree, print out the expression, with parentheses Best traversal: Euler tour If the nodes is an internal node (i.e. an operator): For the pre-order visit, print out “(“ For the in-order visit, print out the operator For the post-order visit, print out “)” If the node is a leaf (i.e. a number): Don’t do anything for pre-order and post-order visits For the in-order visit, print out the number + - / 9 3 7 4 ((7 – (4 + 3)) + (9 / 3))

Analyzing Binary Trees Thursday February 12, 2015 Analyzing Binary Trees As you’ve seen, many things can be modeled as binary trees e.g. recursive calls made by a fibonacci function It’s often helpful to have some stats on binary trees to help analyze our data e.g. how many recursive calls are made if the tree has height h? Perfect binary trees are easy to analyze, so we often use what we know about perfect binary trees to estimate what happens in the general case fib(3) fib(2) fib(1) fib(0) fib(4)

Analyzing Binary Trees (2) Thursday February 12, 2015 Analyzing Binary Trees (2) The number of nodes in a perfect binary tree of height h is 2h+1 – 1 The height of a perfect binary tree with n nodes is log2(n+1) – 1 The number of leaves in a perfect binary tree of height h is 2h The number of nodes in a perfect binary tree with L leaves is 2L – 1

Perfect Binary Tree Proof Thursday February 12, 2015 Perfect Binary Tree Proof Another definition of a perfect binary tree is a binary tree T which has only one node (the root), or has a root with left and right subtrees which are both perfect binary trees of the same height, h, in which case the height of T is h+1 Because we have this recursive definition to work with, proofs on binary trees lend themselves well to induction

Perfect Binary Tree Proof (2) Thursday February 12, 2015 Perfect Binary Tree Proof (2) Prove P(n): The number of nodes in a perfect binary tree of height n is 2n+1 – 1 Base case, P(0): 20+1 – 1 = 2 – 1 = 1 The number of nodes in a perfect binary tree of height 0 is 1, because the tree only has a root by definition Assume P(k), for some k ≥ 0: The number of nodes in a perfect binary tree of height k is 2k+1 – 1 Prove P(k+1): Let T be any perfect binary tree of height k+1 By definition, T consists of a root with two subtrees, L and R, which are both perfect binary trees of height k By our inductive hypothesis, L and R both have 2k+1 – 1 nodes The number of nodes in T is therefore: 1 + 2 * (2k+1 – 1) = 1 + 2k+2 – 2 = 2(k+1)+1 – 1 Since we’ve proved P(0) and P(k)  P(k+1) for any nonnegative k, by induction P(n) is true for all n ≥ 0.