Trees1 Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2010 Goodrich, Tamassia
Trees2 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 Programming environments Computers”R”Us SalesR&DManufacturing LaptopsDesktops US International EuropeAsiaCanada © 2010 Goodrich, Tamassia
Trees3 subtree Tree Terminology Root: node without 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) Ancestors of a node: parent, grandparent, grand-grandparent, etc. Depth of a node: number of ancestors Height of a tree: maximum depth of any node (3) Descendant of a node: child, grandchild, grand-grandchild, etc. A B DC GH E F IJ K Subtree: tree consisting of a node and its descendants © 2010 Goodrich, Tamassia
Examples of Trees File system Internal nodes: directories (folders) External nodes: files © 2010 Goodrich, TamassiaTrees4
5 Tree ADT We use positions to abstract nodes Generic methods: integer size() boolean empty() Accessor methods: position root() list positions() Position-based methods: position p.parent() list p.children() Query methods: boolean p.isRoot() boolean p.isExternal() Additional update methods may be defined for specific applications © 2010 Goodrich, Tamassia position = pointer list = linked list or vector
Trees6 Preorder Traversal A traversal visits the nodes of a tree in a systematic manner In a preorder traversal, a node is visited before its descendants Application: print a structured document Make Money Fast! 1. MotivationsReferences2. Methods 2.1 Stock Fraud 2.2 Ponzi Scheme 1.1 Greed1.2 Avidity 2.3 Bank Robbery Algorithm preOrder(v) visit(v) for each child w of v preorder (w) © 2010 Goodrich, Tamassia
Preorder Traversal: Example © 2010 Goodrich, TamassiaTrees7
8 Postorder Traversal In a postorder traversal, a node is visited after its descendants Application: compute space used by files in a directory and its subdirectories Algorithm postOrder(v) for each child w of v postOrder (w) visit(v) cs16/ homeworks/ todo.txt 1K programs/ DDR.cpp 10K Stocks.cpp 25K h1c.doc 3K h1nc.doc 2K Robot.cpp 20K © 2010 Goodrich, Tamassia
Postorder Traversal: Example © 2010 Goodrich, TamassiaTrees9
Postorder Traversal: Example 2 We want to use postorder traversal to calculate the disk usage of a folder “cs016”. © 2010 Goodrich, TamassiaTrees10
Iterative Implementation of Preorder Traversal Steps 1. Push the root to the stack 2. Pop the stack and visit it 3. Push the children in a reverse order 4. Repeat 2) and 3) until the stack is empty © 2010 Goodrich, TamassiaTrees17
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees18 A B DC GH E F IJ K A Preorder: Stack
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees19 A B DC GH E F IJ K BCDBCD Preorder: A
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees20 A B DC GH E F IJ K EFCDEFCD Preorder: A B
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees21 A B DC GH E F IJ K FCDFCD Preorder: A B E
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees22 A B DC GH E F IJ K IJKCDIJKCD Preorder: A B E F
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees23 A B DC GH E F IJ K JKCDJKCD Preorder: A B E F I
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees24 A B DC GH E F IJ K KCDKCD Preorder: A B E F I J
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees25 A B DC GH E F IJ K CDCD Preorder: A B E F I J k
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees26 A B DC GH E F IJ K GHDGHD Preorder: A B E F I J k C
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees27 A B DC GH E F IJ K HDHD Preorder: A B E F I J k C G
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees28 A B DC GH E F IJ K D Preorder: A B E F I J k C G H
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees29 A B DC GH E F IJ K Preorder: A B E F I J k C G H D
Iterative Implementation of Preorder Traversal: Demo © 2010 Goodrich, TamassiaTrees30 A B DC GH E F IJ K Preorder: A B E F I J k C G H D Done!
Iterative Implementation of Postorder Traversal Steps 1. Push the root node to stack1. 2. Pop a node from stack 1, and push it to stack Then push its children sequentially to stack Repeat step 2) and 3) until stack 1 is empty. 5. Pop all nodes from stack 2 to obtain the traversal in postorder. © 2010 Goodrich, TamassiaTrees31
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees32 A B DC GH E F IJ K A Stack 1Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees33 A B DC GH E F IJ K DCBDCB Stack 1 A Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees34 A B DC GH E F IJ K CBCB Stack 1 DADA Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees35 A B DC GH E F IJ K HGBHGB Stack 1 CDACDA Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees36 A B DC GH E F IJ K GBGB Stack 1 HCDAHCDA Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees37 A B DC GH E F IJ K B Stack 1 GHCDAGHCDA Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees38 A B DC GH E F IJ K FEFE Stack 1 BGHCDABGHCDA Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees39 A B DC GH E F IJ K KJIEKJIE Stack 1 FBGHCDAFBGHCDA Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees40 A B DC GH E F IJ K JIEJIE Stack 1 KFBGHCDAKFBGHCDA Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees41 A B DC GH E F IJ K IEIE Stack 1 JKFBGHCDAJKFBGHCDA Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees42 A B DC GH E F IJ K E Stack 1 IJKFBGHCDAIJKFBGHCDA Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees43 A B DC GH E F IJ K Stack 1 EIJKFBGHCDAEIJKFBGHCDA Stack 2
Iterative Implementation of Postorder Traversal: Demo © 2010 Goodrich, TamassiaTrees44 A B DC GH E F IJ K Stack 1 EIJKFBGHCDAEIJKFBGHCDA Stack 2 Postorder: E I J K F B G H C D A By popping all elements in stack 2
Other Traversal Breadth-first traversal (level-order traversal) Idea: Visit all the nodes at depth d before visiting the nodes at depth d+1 Implementation: Using a queue © 2010 Goodrich, TamassiaTrees45 A B DC GH E F IJ K level-order traversal: A B C D E F G H I J K
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees46 A A B DC GH E F IJ K Output: End Queue Front
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees47 BCD A B DC GH E F IJ K Output: A Queue
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees48 CDEF A B DC GH E F IJ K Output: AB Queue
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees49 DEFGH A B DC GH E F IJ K Output: ABC Queue
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees50 EFGH A B DC GH E F IJ K Output: ABCD Queue
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees51 FGH A B DC GH E F IJ K Output: ABCDE Queue
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees52 GHIJK A B DC GH E F IJ K Output: ABCDEF Queue
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees53 HIJK A B DC GH E F IJ K Output: ABCDEFG Queue
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees54 IJK A B DC GH E F IJ K Output: ABCDEFGH Queue
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees55 JK A B DC GH E F IJ K Output: ABCDEFGHI Queue
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees56 K A B DC GH E F IJ K Output: ABCDEFGHIJ Queue
Breadth-first Traversal: Demo © 2010 Goodrich, TamassiaTrees57 A B DC GH E F IJ K Output: ABCDEFGHIJK Queue Breadth-first traversal!
Trees58 Binary Trees A binary tree is a tree with the following properties: Each internal node has at most two children (exactly two for proper binary trees) The children of a node are an ordered pair We call the children of an internal node left child and right child Alternative recursive definition: a binary tree is either a tree consisting of a single node, or a tree whose root has an ordered pair of children, each of which is a binary tree Applications: arithmetic expressions decision processes searching A B C FG D E H I © 2010 Goodrich, Tamassia
Trees59 Arithmetic Expression Tree Binary tree associated with an arithmetic expression internal nodes: operators external nodes: operands Example: arithmetic expression tree for the expression (2 ( a 1) (3 b)) 2 a1 3b © 2010 Goodrich, Tamassia
Trees60 Decision Tree Binary tree associated with a decision process internal nodes: questions with yes/no answer external nodes: decisions Example: dining decision Want a fast meal? How about coffee?On expense account? StarbucksSpike’sAl FornoCafé Paragon Yes No YesNoYesNo © 2010 Goodrich, Tamassia
Trees61 Properties of Binary Trees Notation n : # of nodes n e : # of external nodes n i : number of internal nodes h : height Properties: h 1 n 2 h+1 1 1 n e 2 h h n i 2 h 1 log 2 (n 1)-1 h n 1 © 2010 Goodrich, Tamassia level=0 level=1 level=2 level=3 Level d has at most 2 d nodes.
Trees62 Properties of Proper Binary Trees Notation n : # of nodes n e : # of external nodes n i : number of internal nodes h : height Properties: 2h 1 n 2 h+1 1 h 1 n e 2 h h n i 2 h 1 log 2 (n 1)-1 h n 1)/2 n e n i 1 © 2010 Goodrich, Tamassia level=0 level=1 level=2 level=3 Level d has at most 2 d nodes. Proper!
Trees63 BinaryTree ADT The BinaryTree ADT extends the Tree ADT, i.e., it inherits all the methods of the Tree ADT Additional methods: position p.left() position p.right() Update methods may be defined by data structures implementing the BinaryTree ADT Proper binary tree: Each node has either 0 or 2 children © 2010 Goodrich, Tamassia
Trees64 Linked Structure for Trees A node is represented by an object storing Element Parent node Sequence of children nodes Node objects implement the Position ADT B D A CE F B ADF C E © 2010 Goodrich, Tamassia
Trees65 Linked Structure for Binary Trees A node is represented by an object storing Element Parent node Left child node Right child node Node objects implement the Position ADT B D A CE B AD CE © 2010 Goodrich, Tamassia
Vector Representation of Binary Trees Nodes of a tree T are stored in an vector S © 2010 Goodrich, Tamassia66Trees Node v is stored at S[f(v)] f(root) = 1 if v is the left child of parent(v), f(v) = 2*f(parent(v)) if v is the right child of parent(v), f(v) = 2*f(parent(v)) A HG FE D C B J ABDGH … … f() is known as level numbering
Vector Representation of Binary Trees: More Examples © 2010 Goodrich, Tamassia67Trees
Vector Representation of Binary Trees: Analysis Notation n: # of nodes in T N: size of S Time complexity Space complexity O(N), which is O(2 n ) in the worse case © 2010 Goodrich, TamassiaTrees68 Major weakness! (So we always want to keep trees as shallow as possible!)
Traversal of Binary Trees TypesInorder traversal: a node is visited after its left subtree and before its right subtree Application: draw a binary tree x(v) = inorder rank of v y(v) = depth of v © 2010 Goodrich, TamassiaTrees
Traversal of Binary Trees Basic types of traversal Preorder Postorder Inorder Level order © 2010 Goodrich, TamassiaTrees70
Postorder Traversal for BT Can be applied to any “bottom-up” evaluation problems Evaluate an arithmetic expression Directory size computation © 2010 Goodrich, TamassiaTrees71
Trees72 Evaluate Arithmetic Expressions Specialization of a postorder traversal recursive method returning the value of a subtree when visiting an internal node, combine the values of the subtrees Algorithm evalExpr(v) if v.isExternal() return v.element() else x evalExpr(v.left()) y evalExpr(v.right()) operator stored at v return x y © 2010 Goodrich, Tamassia Postorder traversal ≡ Postfix notation
Trees73 Inorder Traversal Inorder traversal: a node is visited after its left subtree and before its right subtree Application Draw a binary tree Print arithmetic expressions with parentheses Algorithm inOrder(v) if v.isExternal() inOrder(v.left()) visit(v) if v.isExternal() inOrder(v.right()) © 2010 Goodrich, Tamassia Inorder traversal ≡ Projection!
Inorder Traversal: Examples Properties of inorder traversal Very close to infix notation Can be obtained by tree projection © 2010 Goodrich, TamassiaTrees74
Trees75 Print Arithmetic Expressions Specialization of an inorder traversal print operand or operator when visiting node print “(“ before traversing left subtree print “)“ after traversing right subtree Algorithm printExpression(v) if v.isExternal() print( “(’’ ) inOrder(v.left()) print(v.element()) if v.isExternal() inOrder(v.right()) print ( “)’’ ) 2 a1 3b ((2 ( a 1)) (3 b)) © 2010 Goodrich, Tamassia
Draw a Binary Tree © 2010 Goodrich, TamassiaTrees76 Since inorder traversal is equivalent to tree projection, it is easy to draw a binary tree using inorder traversal.
Trees77 Euler Tour Traversal Generic traversal of a binary tree Includes a special cases the preorder, postorder and inorder traversals Walk around the tree and visit each node three times: on the left (preorder) + x 2 – 5 1 x 3 2 from below (inorder) 2 x 5 – x 2 on the right (postorder) – x 3 2 x + L B R © 2010 Goodrich, Tamassia
Euler Tour Traversal Applications Determine the number of descendants of each node in a tree Fully parenthesize an arithmetic expression from an expression tree © 2010 Goodrich, TamassiaTrees78
From General to Binary Trees How to transform a general tree to a binary tree Left-child right-sibling representation © 2010 Goodrich, TamassiaTrees79