340 likes | 353 Views
Explore the significance of tree structures in computing, their applications in organizing data, and definitions of tree nodes and properties. Learn about tree ADT, formal definitions, ordered trees, and methods in a concise manner.
E N D
Chapter 7 Trees Make Money Fast! BankRobbery StockFraud PonziScheme Trees
7.1 General Trees • Tree is one of the most important non-linear Data Structures in computing. • Tree structures are important because they allow us to implement a host of algorithms much faster than when using linear data structures, such as list. • Trees also provide a natural way to organize data in many areas such as: • File systems • Graphical User Interfaces (GUI) • Databases • Web Sites • and many other computer systems. Trees
Computers”R”Us Sales Manufacturing R&D US International Laptops Desktops Europe Asia Canada What is a Tree? Fig. 7.1. a tree representing the organization of a fictitious corporation Trees
Tree Structure • In computer science, a tree is an abstract model of a hierarchical structure, with some objects being “above” and some “below” others. • A tree consists of nodes with a parent-child relationship, rather than the simple “before” and “after” relationship, found between objects in sequential (linear) structures. • A famous example of hierarchical structure (tree) is the family tree. • Applications: • Organization charts • File systems • Programming environments Trees
7.1.1 Tree Definitions and Properties • Depth of a node: number of its ancestors • Height of a tree: maximum depth of any node • Ancestors of a node: parent, grandparent, grand-grandparent, … etc. • Descendants of a node: child, grandchild, grand-grandchild, … etc. • Subtree: a tree consisting of a node and its descendants • A tree T, is an abstract data type that stores elements hierarchically. • Except the top element (root), each element in a tree has a parent and zero or more children elements. • root: node without parent (Node A) • Internal node: node with at least one child (A, B, C, F) • External node ( leaf ): node without children (E, I, J, K, G, H, D) • Sibling nodes: Two nodes that are children of the same parent are Siblings. Trees
A D B C E G H F K I J Example • Fig.7.2 is an example of a tree T: • T root is node A • Internal (branch) nodes are nodes A, B, C, F • External nodes (leaves) are nodes E, I, J, K, G, H, D • Depth of node F is 2 • Height of T is 3 • Ancestors of node H are C and A • Children of node A are B, C and D • Nodes B, C and D are siblings • Descendants of node B are E, F, I, J and K subtree Fig. 7.2: Example of Tree Trees
Formal Definition of a Tree Formally, we define a tree T as a finite 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 specially designated node, called the root of T, that has no parent. • Each node v of T other than the root has a unique parent node w. • Every node with parentw is a child of w. Note that a tree may be empty. Trees
Recursive Definition of a Tree: A treeT is either empty, or has a finite set of one or more nodes such that: • There is one specially designated node, called the root, and • The remaining nodes, (excluding the root), are partitioned into m ≥ 0 disjoint sets T1 , T2 , …, Tm, and each of these is in turn a tree. • The treesTi (i = 1, 2, …, m) are called the sub-trees of the root. Trees
Subtree of Tree T The subtree of a tree T, rooted at node v is the tree consisting all the descendants of v in T (including v itself). Edges and Paths in Trees: • An edge of treeT 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 any two consecutive nodes in the sequence form an edge. • As an example of a path, (Figure 7.2), is the sequence A, B, F, K. where (A , B) or (B , A) is an edge. Trees
Ordered Trees • A tree is ordered if there is a linear ordering defined for the children of each node; • That’s, we can identify the children of a node as being the first, second, third, and so on. • Such an ordering is usually shown by arranging siblings left to right, according to their ordering. • Ordered trees typically indicate the linear order among siblings by listing them in the correct order. • A famous example of ordered trees is the family tree. Trees
7.1.2 Tree ADT • The tree ADT stores elements at positions, which are defined relative to neighboring positions. • Positions in a tree are its nodes, and the neighboring positions satisfy the parent-child relationships that define a valid tree. • Tree nodes may store arbitrary objects. • As with a list position, a position object for a tree supports the method: element() : that returns the object stored at this position (or node). • The tree ADT supports four types of methods, as follows. Trees
Methods of a Tree ADT • Accessor Methods We use positions to abstract nodes.The real power of node positions in a tree comes from the accessor methods of the tree ADT that return and accept positions, such as the following: • root(): Return the position of the tree’sroot; an error occurs if the tree is empty. • parent(p): Return the position of the parent of p; an error occurs if p is the root. • children(p): Return an iterable collection containing the children of node p. Trees
Notice that: • If a treeT is ordered, then the iterable collection, children(p), stores the children of p in their linear order. • If p is an external node, then children(p) is empty. • Any method that takes a position as argument should generate an error condition if that position is invalid. Trees
Methods of a Tree ADT (Cont.) • Generic methods • size(): Return the number of nodes in the tree. • isEmpty(): Test whether the tree has any nodes or not. • Iterator(): Return an iterator of all the elements stored at nodes of the tree. • positions(): Return an iterable collection of all the nodes of the tree. Trees
Methods of a Tree ADT (Cont.) • Query methods In addition to the above fundamental accessor methods, the tree ADT also supports the following Boolean query methods: • isInternal(p): Test whether node p is an internal node • isExternal(p): Test whether node p is an external node • isRoot(p): Test whether node p is the root node These methods make programming with treeeasier and more readable, since we can use them in the conditionals of if -statements and while -loops, rather than using a non-intuitive conditional. Trees
Methods of a Tree ADT (Cont.) • Update Method The tree ADT also supports the following update method: • replace(p, e): Replace with e and return the element stored at nodep. Additional update methods may be defined by data structures implementing the tree ADT Trees
Tree ADT Exceptions An interface for the tree ADT uses the following exceptions to indicate error conditions: • InvalidPositionException: This error condition may be thrown by any method taking a position as an argument to indicate that the position is invalid. • BoundaryViolationException: This error condition may be thrown by method parent() if it’s called on the root. • EmptyTreeException: This error condition may be thrown by method root() if it’s called on an empty tree. Trees
7.1.3 A Linked Structure for General Trees A natural way to implement a treeT is to use a linked structure, where we represent each node p of T by a position object with the following fields (see Figure): • A reference to the element stored at p. • A link to the parent of p. • A some kind of collection (e.g., a list or array) to store links to the children of p. Trees
7.1.3 Linked Structure for General 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 Trees
Preorder Traversal AlgorithmpreOrder(v) visit(v) foreachchild w of v preOrder (w) • 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, e.g. content list 1 Make Money Fast! 2 5 9 1. Motivations 2. Methods References 6 7 8 3 4 2.3 BankRobbery 2.1 StockFraud 2.2 PonziScheme 1.1 Greed 1.2 Avidity Trees
Postorder Traversal AlgorithmpostOrder(v) foreachchild w of v postOrder (w) visit(v) • In a postorder traversal, a node is visited after its descendants • Application: compute space used by files in a directory and its subdirectories 9 cs16/ 8 3 7 todo.txt1K homeworks/ programs/ 4 5 6 1 2 Robot.java20K h1c.doc3K h1nc.doc2K DDR.java10K Stocks.java25K Trees
Binary Trees (§ 6.3) • Applications: • arithmetic expressions • decision processes • searching • 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 A C B D E F G I H Trees
+ 2 - 3 b a 1 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)) 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? No Yes How about coffee? On expense account? Yes No Yes No Starbucks Spike’s Al Forno Café Paragon Trees
Properties of Proper Binary Trees • Properties: • e = i +1 • n =2e -1 • h i • h (n -1)/2 • e 2h • h log2e • h log2 (n +1)-1 • Notation n number of nodes e number of external nodes i number of internal nodes h height Trees
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) boolean hasLeft(p) boolean hasRight(p) Update methods may be defined by data structures implementing the BinaryTree ADT BinaryTree ADT (§ 6.3.1) Trees
Inorder Traversal AlgorithminOrder(v) ifhasLeft (v) inOrder (left (v)) visit(v) ifhasRight (v) inOrder (right (v)) • 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 6 2 8 1 4 7 9 3 5 Trees
+ 2 - 3 b a 1 Print Arithmetic Expressions AlgorithmprintExpression(v) ifhasLeft (v)print(“(’’) inOrder (left(v)) print(v.element ()) ifhasRight (v) 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)) Trees
+ 2 - 3 2 5 1 Evaluate Arithmetic Expressions AlgorithmevalExpr(v) ifisExternal (v) returnv.element () else x evalExpr(leftChild (v)) y evalExpr(rightChild (v)) operator stored at v returnx y • Specialization of a postorder traversal • recursive method returning the value of a subtree • when visiting an internal node, combine the values of the subtrees Trees
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 B 2 - 3 2 5 1 Trees
Template Method Pattern public abstract class EulerTour{ protected BinaryTree tree;protected voidvisitExternal(Position p, Result r) { }protected voidvisitLeft(Position p, Result r) { }protected voidvisitBelow(Position p, Result r) { }protected voidvisitRight(Position p, Result r) { }protected Object eulerTour(Position p) { Result r = new Result();if tree.isExternal(p) { visitExternal(p, r); }else {visitLeft(p, r); r.leftResult = eulerTour(tree.left(p));visitBelow(p, r); r.rightResult = eulerTour(tree.right(p)); visitRight(p, r);return r.finalResult; } … • Generic algorithm that can be specialized by redefining certain steps • Implemented by means of an abstract Java class • Visit methods that can be redefined by subclasses • Template method eulerTour • Recursively called on the left and right children • A Result object with fields leftResult, rightResult and finalResult keeps track of the output of the recursive calls to eulerTour Trees
Specializations of EulerTour public class EvaluateExpressionextends EulerTour{ protected voidvisitExternal(Position p, Result r) {r.finalResult = (Integer) p.element(); } protected voidvisitRight(Position p, Result r) {Operator op = (Operator) p.element();r.finalResult = op.operation( (Integer) r.leftResult, (Integer) r.rightResult ); } … } • We show how to specialize class EulerTour to evaluate an arithmetic expression • Assumptions • External nodes store Integer objects • Internal nodes store Operator objects supporting method operation (Integer, Integer) Trees
D C A B E 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 C E Trees
A … B D C E F J G H Array-Based Representation of Binary Trees • nodes are stored in an array 1 2 3 • let rank(node) be defined as follows: • 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 10 11 Trees