1 / 49

Understanding Trees in Computer Science

Learn about trees in computer science, their structure, terminology, and applications. Explore the Tree ADT, terminology, methods, and running time assumptions. Discover how to find the depth and height of nodes in a tree.

pcamarillo
Download Presentation

Understanding Trees in Computer Science

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Trees Make Money Fast! BankRobbery StockFraud PonziScheme Trees

  2. Computers”R”Us Sales Manufacturing R&D US International Laptops Desktops Europe Asia Canada 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 Trees

  3. A C D B E G H F K I J 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 an external node (3) • Descendant of a node: child, grandchild, grand-grandchild, etc. • Subtree: tree consisting of a node and its descendants subtree Trees

  4. More Terminology v v Internal node = node with one or more children External node = node with no children Leaf = external node Subtree rooted at v Trees (Goodrich, 268)‏ Siblings = two or more nodes that are children of the same parent

  5. Tree ADT • Query methods: • boolean isInternal(p) • boolean isExternal(p) • boolean isRoot(p) • Update method: • element replace (p, o) • Additional update methods may be defined by data structures implementing the 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) Trees

  6. Tree Interface Trees (Goodrich, 270)‏ public interface Tree<E> { public int size(); public boolean isEmpty(); public Iterator<E> iterator(); public Iterable<Position<E>> positions(); public E replace(Position<E> v, E e)throws InvalidPositionException; public Position<E> root() throws EmptyTreeException; public Position<E> parent(Position<E> v)throws InvalidPositionException, BoundaryViolationException; public Iterable<Position<E>> children(Position<E> v) throws InvalidPositionException; public boolean isInternal(Position<E> v) throws InvalidPositionException; public boolean isExternal(Position<E> v) throws InvalidPositionException; public boolean isRoot(Position<E> v)throws InvalidPositionException; }

  7. Running Time Assumptions Method Time root O(1)‏ parent O(1)‏ isInternal, isExternal O(1)‏ isRoot O(1)‏ children O(cv) (cv = no. of children of v)‏ swapElements O(1)‏ replace O(1)‏ iterator, positions O(n)‏ Trees (Goodrich, 272)‏

  8. Depth of a Node in a Tree Depth of v = number of ancestors of v If v is the root, v’s depth = 0 Else, v’s depth = 1 + depth of v’s parent Trees (Goodrich, 273)‏ Depth 0 1 + depth( myParent ) = 1 + 0 = 1 1 + depth( myParent ) = 1 + 1 = 2 1 + depth( myParent ) = 1 + 2 = 3

  9. Finding the Depth Algorithm depth( T, v )‏ if T.isRoot(v) then return 0 else return 1 + depth( T, T.parent(v) )‏ Trees (Goodrich, 273)‏

  10. Finding the Depth Algorithm depth( T, v )‏ if T.isRoot(v) then return 0 else return 1 + depth( T, T.parent(v) )‏ Trees (Goodrich, 273)‏ public static <E> int depth(Tree<E> T, Position<E> v){ if( T.isRoot(v) )‏ return 0; else return 1 + depth( T, T.parent(v) ); }

  11. Height Height of node v If v is an external node, v’s height = 0 Else, v’s height = 1 + maximum height of v’s children Trees (Goodrich, 274–275)‏ hv = 1 + max( h of myChildren ) hv = 1 + 1 = 2 v h = 1 + max( h of myChildren )‏ h = 1 + 0 = 1 h = 0 (External node)‏ h = 0 (External node)‏

  12. Height Height of node v If v is an external node, v’s height = 0 Else, v’s height = 1 + maximum height of v’s children Trees (Goodrich, 274–275)‏ hv = 1 + max( h of myChildren ) hv = 1 + 1 = 2 v h = 1 + max( h of myChildren )‏ h = 1 + 0 = 1 h = 0 (External node)‏ h = 0 (External node)‏ • Height of tree T • T’s height = height of the root of T

  13. Finding the Height of a Tree Algorithm height( T, root )‏ if T.isExternal(root) then return 0 else h = 0 for each node  T.children(root) do h = max( h, height(T,node) )‏ return 1 + h r t u v r h = 0 h = max(h,height(T,t))‏ return 1 + h Trees (Goodrich, 274–275)‏ T 2 1 0 0

  14. Finding the Height of a Tree Algorithm height( T, root )‏ if T.isExternal(root) then return 0 else h = 0 for each node  T.children(root) do h = max( h, height(T,node) )‏ return 1 + h r t u v r h = 0 h = max(h,height(T,t))‏ return 1 + h t h = 0 h = max(h,height(T,u))‏ h = max(h,height(T,v))‏ return 1 + h Trees (Goodrich, 274–275)‏ T 2 1 0 0

  15. Finding the Height of a Tree Algorithm height( T, root )‏ if T.isExternal(root) then return 0 else h = 0 for each node  T.children(root) do h = max( h, height(T,node) )‏ return 1 + h r t u v r h = 0 h = max(h,height(T,t))‏ return 1 + h t h = 0 h = max(h,height(T,u))‏ h = max(h,height(T,v))‏ return 1 + h return 0 u return 0 Trees (Goodrich, 274–275)‏ T 2 1 0 0

  16. Finding the Height of a Tree Algorithm height( T, root )‏ if T.isExternal(root) then return 0 else h = 0 for each node  T.children(root) do h = max( h, height(T,node) )‏ return 1 + h r t u v r h = 0 h = max(h,height(T,t))‏ return 1 + h t h = 0 h = max(h,height(T,u))‏ h = max(h,height(T,v))‏ return 1 + h return 0 return 0 u return 0 v return 0 Trees (Goodrich, 274–275)‏ T 2 1 0 0

  17. Finding the Height of a Tree Algorithm height( T, root )‏ if T.isExternal(root) then return 0 else h = 0 for each node  T.children(root) do h = max( h, height(T,node) )‏ return 1 + h r t u v r h = 0 h = max(h,height(T,t))‏ return 1 + h return 1 t h = 0 h = max(h,height(T,u))‏ h = max(h,height(T,v))‏ return 1 + h return 0 return 0 u return 0 v return 0 Trees (Goodrich, 274–275)‏ T 2 1 0 0

  18. Finding the Height of a Tree Algorithm height( T, root )‏ if T.isExternal(root) then return 0 else h = 0 for each node  T.children(root) do h = max( h, height(T,node) )‏ return 1 + h r t u v r h = 0 h = max(h,height(T,t))‏ return 1 + h return 1 t h = 0 h = max(h,height(T,u))‏ h = max(h,height(T,v))‏ return 1 + h return 0 return 0 u return 0 v return 0 Trees (Goodrich, 274–275)‏ T 2 1 return 2 0 0

  19. 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 AlgorithmpreOrder(v) visit(v) foreachchild w of v preorder (w) 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

  20. 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 AlgorithmpostOrder(v) foreachchild w of v postOrder (w) visit(v) 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

  21. Binary Trees • 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

  22. +   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

  23. 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

  24. 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 log2e • h log2 (n +1)-1 Trees

  25. Level d has at most 2d nodes Trees

  26. 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 Trees

  27. 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

  28. +   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

  29. +   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

  30. 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

  31. 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 Trees

  32. 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

  33. Array-Based Representation of Binary Trees • Nodes are stored in an array A 1 A … A B D … G H 2 3 0 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 C E F J 10 11 G H Trees

  34. Implementing a Binary Tree

  35. Linked Binary Tree Natural way to represent a tree is by using linked nodes Trees (Goodrich, 287–295)‏

  36. Node for a Binary Tree left parent right element Trees (Goodrich, 287–295)‏

  37. Node for a Binary Tree left parent right element root left null right r null parent null null parent null s t Trees (Goodrich, 287–295)‏

  38. Node for a Binary Tree public classBTNode<E> implements BTPosition { private E element; public BTNode() { } public BTNode(E element, BTPosition<E> parent, BTPosition<E> left, BTPosition<E> right) { setElement(element); setParent(parent); setLeft(left); setRight(right); } public E element() { return element; } public void setElement(E o) { element=o; } public BTPosition<E> getLeft() { return left; } public void setLeft(BTPosition<E> v) { left=v; } public BTPosition<E> getRight() { return right; } public void setRight(BTPosition<E> v) { right=v; } public BTPosition<E> getParent() { return parent; } public void setParent(BTPosition<E> v) { parent=v; } } Trees (Goodrich, 287–295)‏

  39. Position for a Binary Tree public interfaceBTPosition<E> extends Position<E>{ // inherits element()‏ public void setElement(E o); public BTPosition<E> getLeft(); public void setLeft(BTPosition<E> v); public BTPosition<E> getRight(); public void setRight(BTPosition<E> v); public BTPosition<E> getParent(); public void setParent(BTPosition<E> v); } Trees (Goodrich, 287–295)‏

  40. A Position Interface public interface Position<E> { /** Return the element stored at this position. */ E element(); } A Position object, has only one operation that it can use. This operation returns the element stored inside the object. Positions (Goodrich, 232, 234)‏

  41. Some Operations of a Binary TreeReturn to pages 304 - 308 public class LinkedBinaryTree<E> implements BinaryTree<E> { public int size() {return size; } public boolean isEmpty() { /*...*/ } public boolean isInternal(Position<E> v) throws InvalidPositionException { checkPosition(v); return (hasLeft(v) || hasRight(v)); } public boolean isExternal(Position<E> v) throws InvalidPositionException { /*...*/ } public boolean isRoot(Position<E> v) throws InvalidPositionException { checkPosition(v); return (v == root()); } public boolean hasLeft(Position<E> v) throws InvalidPositionException { BTPosition<E> vv = checkPosition(v); return (vv.getLeft() != null); } public boolean hasRight(Position<E> v) throws InvalidPositionException { /*...*/ } public Position<E> root() throws EmptyTreeException { /*...*/ } public Position<E> left(Position<E> v) throws InvalidPositionException, BoundaryViolationException { BTPosition<E> vv = checkPosition(v); Position<E> leftPos = vv.getLeft(); if (leftPos == null) throw new BoundaryViolationException(); return leftPos;} public Position<E> right(Position<E> v) throws InvalidPositionException, BoundaryViolationException { /*...*/ } Trees (Goodrich, 287–295)‏

  42. Instance Variablesof a Binary Tree public class LinkedBinaryTree<E> implements BinaryTree<E> { protected BTPosition<E> root; // reference to the root protected int size; // number of nodes //... Trees (Goodrich, 287–295)‏

  43. Constructor of a Binary Tree public class LinkedBinaryTree<E> implements BinaryTree<E> { protected BTPosition<E> root; // reference to the root protected int size; // number of nodes public LinkedBinaryTree() { root = null; // start with an empty tree size = 0; } //... Trees (Goodrich, 287–295)‏

  44. Operations of the LinkedBinaryTree Tell us about the positions pos root()‏ pos parent( pos )‏ iter children( pos )‏ bool isInternal( pos )‏ bool isExternal( pos )‏ bool isRoot( pos )‏ pos left( pos )‏ pos right( pos )‏ pos hasLeft( pos )‏ pos hasRight( pos )‏ pos sibling( pos )‏ Trees (Goodrich, 289–295)‏ • Tell us about the collection int size()‏ bool isEmpty()‏ iter iterator()‏ iter positions()‏ • Update the data void replace( pos, e )‏ addRoot( e )‏ insertLeft( pos, e )‏ insertRight( pos, e )‏ remove( pos )‏ Tree methods Binary Tree methods Additional methods

  45. Adding an Element to a LinkedBinaryTree Object root Adds a node as root and fills it with an element. T.addRoot(new Character('A')); A Trees (Goodrich, 287–295)‏ root Creates an empty tree. LinkedBinaryTree<Character> T = new LinkedBinaryTree<Character>;

  46. Adding an Element to a LinkedBinaryTree Object root Adds a node as root and fills it with an element. T.addRoot(new Character('A')); A root Inserts the node with its element. T.insertLeft( T.root(), new Character('B')); A B Trees (Goodrich, 287–295)‏ root Creates an empty tree. LinkedBinaryTree<Character> T = new LinkedBinaryTree<Character>;

  47. ArrayList Implementation An Alternative Binary Tree Implementation

  48. Binary TreeImplemented with an ArrayList While it’s natural to think of implementing a tree with linked Nodes, a binary tree can also be implemented with an ArrayList Advantage: better performance Trees (Goodrich, 296–297)‏

  49. Binary TreeImplemented as an ArrayList Based on a way of numbering the nodes If v is the root of T, then p(v) = 1 If v is the left child of node u, then p(v) = 2 * p(u)‏ If v is the right child of node u, then p(v) = 2 * p(u) + 1 D B F A C E G Trees (Goodrich, 289–291)‏ 1 D 3 2 B F 7 A C E 6 G 5 4 A 0 1 2 3 4 5 6 7 8 9

More Related