© 2013 Goodrich, Tamassia, Goldwasser Trees 9/13/2018 10:55 PM Trees Make Money Fast! Stock Fraud Ponzi Scheme Bank Robbery © 2013 Goodrich, Tamassia, Goldwasser Trees
Assignment #7: Linked Lists C-7.29 Describe in detail an algorithm for reversing a singly linked list L using only a constant amount of additional space and not using any recursion. C-7.37 Implement a function that accepts a PositionalList L of n integers sorted in nondecreasing order, and another value V, and determines in O(n) time if there are two elements of L that sum precisely to V. The function should return a pair of positions of such elements, if found, or None otherwise. P-7.47 Implement a CardHand class that supports a person arranging a group of cards in his or her hand. The simulator should represent the sequence of cards using a single positional list ADT so that cards of the same suit are kept together. Implement this strategy by means of four "fingers" into the hand, one for each of the suits of hearts, clubs, spades, and diamonds, so that adding a new card to the person's hand or playing a correct card from the hand can be done in constant time. The class should support the following methods: add_card(r, s): Add a new card with rank r and suit s to the hand. play(s): Remove and return a card of suit s from the player's hand; if there is no card of suit s, then remove and return an arbitrary card from the hand. __iter__(): Iterate through all cards currently in the hand. all_of_suit(s): Iterate through all cards of suit s that are currently in the hand.
C-7.19
C-7.37
Trees 9/13/2018 10:55 PM P-7.47 化学与分子工程学院 陈世祺
Trees 9/13/2018 10:55 PM P-7.47 化学与分子工程学院 陈世祺
General tree Productivity experts say that breakthroughs come by thinking “nonlinearly.” referring to an organizational relationship that is richer than the simple “before” and “after” relationships between objects in sequences. Tree structures allow us to implement a host of algorithms much faster than when using linear data structures, such as array-based lists or linked lists.
Trees 9/13/2018 10:55 PM The relationships in a tree are hierarchical, with some objects being “above” and some “below” others.
© 2013 Goodrich, Tamassia, Goldwasser 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 © 2013 Goodrich, Tamassia, Goldwasser Trees
Formal Tree Definition define a tree T as a set of nodes storing elements such that the nodes have a parent-child relationship that satisfies the following properties: If T is nonempty, it has a special node, called the root of T, that has no parent. Each node v of T different from the root has a unique parent node w; every node with parent w is a child of w.
Define a tree recursively a tree T is either empty or consists of a node r, called the root of T, and a (possibly empty) set of subtrees whose roots are the children of r.
© 2013 Goodrich, Tamassia, Goldwasser Trees 9/13/2018 10:55 PM 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. Subtree: tree consisting of a node and its descendants A B D C G H E F I J K subtree The height of a position p in a tree T is also defined recursively: • If p is a leaf, then the height of p is 0. • Otherwise, the height of p is one more than the maximum of the heights of p’s children. The height of a nonempty tree T is the height of the root of T. For example, the tree of Figure 8.2 has height 4. In addition, height can also be viewed as follows. Proposition 8.4: The height of a nonempty tree T is equal to the maximum of the depths of its leaf positions. © 2013 Goodrich, Tamassia, Goldwasser Trees
Other Node Relationships Two nodes that are children of the same parent are siblings.
Edges and Paths in Trees An edge of tree T is a pair of nodes (u,v) such that u is the parent of v, or vice versa. A path of T is a sequence of nodes such that any two consecutive nodes in the sequence form an edge. For example, the tree in Figure 8.3 contains the path (cs252/, projects/, demos/, market).
preview of the remainder of this chapter
Ordered Trees A tree is ordered if there is a meaningful linear order among the children of each node; A family tree that describes generational relationships is often modeled as an ordered tree, with siblings ordered according to their birth. In contrast, an organizational chart for a company is typically considered an unordered tree. Likewise, when using a tree to describe an inheritance hierarchy, there is no particular significance to the order among the subclasses of a parent class.
© 2013 Goodrich, Tamassia, Goldwasser Trees 9/13/2018 10:55 PM Tree ADT We use positions to abstract nodes Generic methods: Integer len() Boolean is_empty() Iterator positions() Iterator iter() Accessor methods: position root() position parent(p) Iterator children(p) Integer num_children(p) Query methods: Boolean is_leaf(p) Boolean is_root(p) Update method: element replace (p, o) Additional update methods may be defined by data structures implementing the Tree ADT An element is stored at each position, and positions satisfy parent-child relationships that define the tree structure. A position object for a tree supports the method: p.element( ): Return the element stored at position p. © 2013 Goodrich, Tamassia, Goldwasser Trees
Abstract Tree Class in Python © 2013 Goodrich, Tamassia, Goldwasser Trees
© 2013 Goodrich, Tamassia, Goldwasser Trees 9/13/2018 10:55 PM 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 Algorithm preOrder(v) visit(v) for each child w of v preorder (w) 1 Make Money Fast! 2 5 9 A traversal of a tree T is a systematic way of accessing, or “visiting,” all the positions of T. The specific action associated with the “visit” of a position p depends on the application of this traversal, and could involve anything from incrementing a counter to performing some complex computation for p. In this section, we describe several common traversal schemes for trees, implement them in the context of our various tree classes, and discuss several common applications of tree traversals. 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 © 2013 Goodrich, Tamassia, Goldwasser Trees
© 2013 Goodrich, Tamassia, Goldwasser 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) 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 © 2013 Goodrich, Tamassia, Goldwasser Trees
© 2013 Goodrich, Tamassia, Goldwasser 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 D E F G H I © 2013 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 © 2013 Goodrich, Tamassia, Goldwasser Trees
© 2013 Goodrich, Tamassia, Goldwasser 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 Spike’s Al Forno Café Paragon © 2013 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 © 2013 Goodrich, Tamassia, Goldwasser Trees
© 2013 Goodrich, Tamassia, Goldwasser 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) Update methods may be defined by data structures implementing the BinaryTree ADT © 2013 Goodrich, Tamassia, Goldwasser Trees
© 2013 Goodrich, Tamassia, Goldwasser Inorder Traversal 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 v has a left child inOrder (left (v)) visit(v) if v has a right child inOrder (right (v)) 6 2 8 1 4 7 9 3 5 © 2013 Goodrich, Tamassia, Goldwasser Trees
Print Arithmetic Expressions Algorithm printExpression(v) if v has a left child print(“(’’) inOrder (left(v)) print(v.element ()) if v has a right child 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)) © 2013 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 is_leaf (v) return v.element () else x evalExpr(left (v)) y evalExpr(right (v)) operator stored at v return x y + - 2 5 1 3 © 2013 Goodrich, Tamassia, Goldwasser Trees
© 2013 Goodrich, Tamassia, Goldwasser Trees 9/13/2018 10:55 PM 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) from below (inorder) on the right (postorder) + L R we start by going from the root toward its leftmost child, viewing the edges of T as being “walls” that we always keep to our left. B 2 - 3 2 5 1 © 2013 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 © 2013 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 © 2013 Goodrich, Tamassia, Goldwasser Trees
Array-Based Representation of Binary Trees Nodes are stored in an array A 1 A A B D … G H … 2 3 1 2 3 10 11 B D Node v is stored at A[rank(v)] rank(root) = 1 if node is the left child of parent(node), rank(node) = 2 rank(parent(node)) if node is the right child of parent(node), rank(node) = 2 rank(parent(node)) + 1 4 5 6 7 E F C J 10 11 G H © 2013 Goodrich, Tamassia, Goldwasser Trees