Trees 5/2/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, Wiley, 2014 Trees Mammal Dog Pig Cat © 2014 Goodrich, Tamassia, Goldwasser 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 Applications: Organization charts File systems Programming environments Computers”R”Us Sales R&D Manufacturing Laptops Desktops US International Europe Asia Canada © 2014 Goodrich, Tamassia, Goldwasser Trees
Tree Terminology subtree Root Internal node node without parent (A) Internal node node with at least one child (A, B, C, F) Leaf (a.k.a. external node) node without children (E, I, J, K, G, H, D) Ancestors of a node parent, grandparent, grand-grandparent, etc. Descendants of a node child, grandchild, … A B D C G H E F I J K subtree © 2014 Goodrich, Tamassia, Goldwasser Trees
Tree Terminology subtree Depth of a node Height of a tree Subtree number of ancestors Height of a tree maximum depth of any node (3) Subtree tree consisting of a node and its descendants A B D C G H E F I J K subtree © 2014 Goodrich, Tamassia, Goldwasser Trees
Tree ADT We use “positions” to abstract nodes Generic methods: integer size() boolean isEmpty() Iterator iterator() Iterable positions() Accessor methods: position root() position parent(p) Iterable children(p) Integer numChildren(p) Query methods: boolean isInternal(p) boolean isExternal(p) boolean isRoot(p) Additional update methods may be defined by data structures implementing the Tree ADT © 2014 Goodrich, Tamassia, Goldwasser Trees
Binary Trees Properties: Applications: Each internal node has at most two children exactly two for proper binary trees children of a node are an ordered pair 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 D E F G H I © 2014 Goodrich, Tamassia, Goldwasser Trees
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 a 1 3 b © 2014 Goodrich, Tamassia, Goldwasser Trees
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? Yes No How about coffee? On expense account? Yes No Yes No Starbucks Chipotle Gracie’s Café Paragon © 2014 Goodrich, Tamassia, Goldwasser Trees
Properties of Proper Binary Trees Notation n number of nodes e number of external nodes i number of internal nodes h height Properties: e = i + 1 n = 2e - 1 h i h (n - 1)/2 e 2h h log2 e h log2 (n + 1) - 1 © 2014 Goodrich, Tamassia, Goldwasser Trees
BinaryTree ADT The BinaryTree ADT extends the Tree ADT, i.e., it inherits all the methods of the Tree ADT Additional methods: position left(p) position right(p) position sibling(p) The above methods return null when there is no left, right, or sibling of p, respectively Update methods may be defined by data structures implementing the BinaryTree ADT © 2014 Goodrich, Tamassia, Goldwasser Trees
Implementing Trees How to store a tree? © 2014 Goodrich, Tamassia, Goldwasser Trees
Binary trees How would your store this tree? B A D C E © 2014 Goodrich, Tamassia, Goldwasser Trees
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 A D B A D C E C E © 2014 Goodrich, Tamassia, Goldwasser Trees
Array-Based Representation of Binary Trees Nodes are stored in an array A A A B D … G H … 1 2 1 2 9 10 B D Node v is stored at A[rank(v)] rank(root) = 0 if node is the left child of parent(node), rank(node) = 2 rank(parent(node)) + 1 if node is the right child of parent(node), rank(node) = 2 rank(parent(node)) + 2 3 4 5 6 E F C J 9 10 G H © 2014 Goodrich, Tamassia, Goldwasser Trees
Array-Based Representation of Binary Trees Given rank(node), how to find rank(parent(node))? Nodes are stored in an array A A A B D … G H … 1 2 1 2 9 10 B D Node v is stored at A[rank(v)] rank(root) = 0 if node is the left child of parent(node), rank(node) = 2 rank(parent(node)) + 1 if node is the right child of parent(node), rank(node) = 2 rank(parent(node)) + 2 3 4 5 6 E F C J 9 10 G H © 2014 Goodrich, Tamassia, Goldwasser Trees
Linked structure vs. Array-Based Besides the typical tradeoffs Max size for array Extra space to store pointers for linked structure What else in terms of space? A 1 2 B D 3 4 5 6 E F C J 9 10 G H © 2014 Goodrich, Tamassia, Goldwasser Trees
[or rightChild(node)] Time Complexity Operation Linked Structure Array-based leftChild(node) [or rightChild(node)] Parent(node) © 2014 Goodrich, Tamassia, Goldwasser Trees
[or rightChild(node)] Time Complexity Operation Linked Structure Array-based leftChild(node) [or rightChild(node)] O(1) Parent(node) © 2014 Goodrich, Tamassia, Goldwasser Trees
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 A D F B A D F C E C E © 2014 Goodrich, Tamassia, Goldwasser Trees
Traversing a Tree Systematically visiting all tree nodes Help find a particular node Help print the tree … © 2014 Goodrich, Tamassia, Goldwasser Trees
Traversal Systemically visit each element in the data structure Arrays increment index Linked lists follow “next” pointer Tree What would you do? In O(n) time © 2014 Goodrich, Tamassia, Goldwasser Trees
Preorder Traversal Algorithm preOrder(v) visit(v) In a preorder traversal a node is visited before its descendants Application: print a structured document AKA: Depth-first Traversal Algorithm preOrder(v) visit(v) for each child w of v preorder (w) 1 Make Money Fast! 2 5 9 1. Motivations 2. Methods References 6 7 8 3 4 2.1 Stock Fraud 2.2 Ponzi Scheme 2.3 Bank Robbery 1.1 Greed 1.2 Avidity © 2014 Goodrich, Tamassia, Goldwasser Trees
Preorder Traversal Decomposition? Base case? Composition? In a preorder traversal a node is visited before its descendants Application: print a structured document AKA: Depth-first Traversal Algorithm preOrder(v) visit(v) for each child w of v preorder (w) 1 Make Money Fast! 2 5 9 1. Motivations 2. Methods References 6 7 8 3 4 2.1 Stock Fraud 2.2 Ponzi Scheme 2.3 Bank Robbery 1.1 Greed 1.2 Avidity © 2014 Goodrich, Tamassia, Goldwasser Trees
Postorder Traversal Algorithm postOrder(v) for each child w of v 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) 9 cs16/ 8 3 7 todo.txt 1K homeworks/ programs/ 1 2 4 5 6 h1c.doc 3K h1nc.doc 2K DDR.java 10K Stocks.java 25K Robot.java 20K © 2014 Goodrich, Tamassia, Goldwasser Trees
Postorder Traversal Decomposition? Base case? Composition? 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) 9 cs16/ 8 3 7 todo.txt 1K homeworks/ programs/ 1 2 4 5 6 h1c.doc 3K h1nc.doc 2K DDR.java 10K Stocks.java 25K Robot.java 20K © 2014 Goodrich, Tamassia, Goldwasser Trees
Inorder Traversal Algorithm inOrder(v) if left (v) ≠ null In an inorder 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 Algorithm inOrder(v) if left (v) ≠ null inOrder (left (v)) visit(v) if right(v) ≠ null inOrder (right (v)) 6 2 8 1 4 7 9 3 5 © 2014 Goodrich, Tamassia, Goldwasser Trees
Inorder Traversal Decomposition? Base case? Composition? In an inorder 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 Algorithm inOrder(v) if left (v) ≠ null inOrder (left (v)) visit(v) if right(v) ≠ null inOrder (right (v)) 6 2 8 1 4 7 9 3 5 © 2014 Goodrich, Tamassia, Goldwasser Trees
Print Arithmetic Expressions Algorithm printExpression(v) if left (v) ≠ null print(“(’’) inOrder (left(v)) print(v.element ()) if right(v) ≠ null inOrder (right(v)) print (“)’’) Specialization of an inorder traversal print operand or operator when visiting node print “(“ before traversing left subtree print “)“ after traversing right subtree + - 2 a 1 3 b ((2 (a - 1)) + (3 b)) © 2014 Goodrich, Tamassia, Goldwasser Trees
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 isExternal (v) return v.element () else x evalExpr(left(v)) y evalExpr(right(v)) operator stored at v return x y + - 2 5 1 3 © 2014 Goodrich, Tamassia, Goldwasser Trees
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 isExternal (v) return v.element () else x evalExpr(left(v)) y evalExpr(right(v)) operator stored at v return x y + - 2 5 1 3 Decomposition? Base case? Composition? © 2014 Goodrich, Tamassia, Goldwasser Trees
Breadth-first Traversal Visit nodes at depth d before nodes at depth d+1 “level by level, left to right” © 2014 Goodrich, Tamassia, Goldwasser Trees
Breadth-first Traversal Visit nodes at depth d before nodes at depth d+1 Algorithm? Hint: use a queue © 2014 Goodrich, Tamassia, Goldwasser Trees
Drawing a Tree Shapes for the nodes are easier to draw—lines and circles Where to put the nodes could be challenging © 2014 Goodrich, Tamassia, Goldwasser Trees
Drawing a Tree What corresponds to the x-value of a node? (hint: one of the traversals)? What corresponds to the y-value of a node? © 2014 Goodrich, Tamassia, Goldwasser Trees
Depth of Every Node Print each node and its depth Use in-order traversal Because we need in-order traversal later Algorithm in pseudocode? © 2014 Goodrich, Tamassia, Goldwasser Trees
Depth of Every Node printDepth(root, 0) d = depth of node (consistent with the book) printDepth(node, d) if leftChild printDepth(leftChild, d+1) print node, d if rightChild printDepth(rightChild, d+1) printDepth(root, 0) © 2014 Goodrich, Tamassia, Goldwasser Trees
In-order Traversal Rank Print each node and its in-order traversal rank © 2014 Goodrich, Tamassia, Goldwasser Trees
In-order Traversal Rank x = in-order traversal rank (consistent with the book) inOrderRank(node, x) if leftChild x = inOrderRank(leftChild, x) print node, x x++ if rightChild x = inOrderRank(rightChild, x) return x inOrderRank(root, 0) © 2014 Goodrich, Tamassia, Goldwasser Trees
Drawing a Tree For each node, instead of printing depth (d) and in-order traversal rank (x) Draw each node at coordinates X-value = x Y-value = d Ie. at (x, d) © 2014 Goodrich, Tamassia, Goldwasser Trees
Drawing a Tree drawTree(root, 0, 0) x = in-order traversal rank (x value, consistent with the book) d = depth of node (y value, consistent with the book) drawTree(node, d, x) if leftChild x = drawTree(leftChild, d+1, x) draw node at (x, d) x++ if rightChild x = drawTree(rightChild, d+1, x) return x drawTree(root, 0, 0) © 2014 Goodrich, Tamassia, Goldwasser Trees
Skip (Euler Tour Traversal) Generalized traversal “Walk around the tree” and visit each node three times: on the left (preorder) from below (inorder) on the right (postorder) + L R B 2 - 3 2 5 1 © 2014 Goodrich, Tamassia, Goldwasser Trees