/
The Tree ADT 10- 2 Objectives The Tree ADT 10- 2 Objectives

The Tree ADT 10- 2 Objectives - PowerPoint Presentation

linda
linda . @linda
Follow
66 views
Uploaded On 2023-10-25

The Tree ADT 10- 2 Objectives - PPT Presentation

Define trees as data structures Discuss tree traversal algorithms Discuss a binary tree implementation 10 3 Trees A tree is a nonlinear abstract data type that stores elements in a hierarchy ID: 1024447

node tree expression root tree node root expression order traversal binary nodes left empty inorder iterator null element public

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "The Tree ADT 10- 2 Objectives" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1. The Tree ADT

2. 10-2ObjectivesDefine trees as data structuresDiscuss tree traversal algorithmsDiscuss a binary tree implementation

3. 10-3TreesA tree is a nonlinear abstract data type that stores elements in a hierarchy.Examples in real life: Family treeTable of contents of a bookClass inheritance hierarchy in JavaComputer file system (folders and subfolders)Decision trees

4. 10-4Example: Computer File SystemRoot directory of C driveDocuments and SettingsProgram FilesMy MusicDesktopFavoritesStart MenuMicrosoft OfficeAdobe

5. 10-5Example: Table of ContentsJava Software StructuresIntroductionAnalysis of AlgorithmsIndexSoftware QualityData StructuresAlgorithm EfficiencyTime ComplexityBig Oh Notatio

6. 3-6Example: Java’s Class HierarchyErrorObjectExceptionSquareStringRectangleThrowableArray. . .......

7. 10-7 Tree DefinitionA tree is a set of elements that eitherit is empty, orit has a distinguished element called the root and zero or more trees (called subtrees of the root)What kind of definition is this?What is the base case?What is the recursive part?

8. 10-8Tree DefinitionSubtrees of the root Root

9. 10-9Tree TerminologyNodes: the elements in the treeEdges: connections between nodesRoot: the distinguished element that is the origin of the treeThere is only one root node in a treeEmpty tree has no nodes and no edges

10. 10-10Tree Terminologynode or vertexRootedgearc, orlink

11. 10-11Parent or predecessor: the node directly above another node in the hierarchyA node can have only one parentChild or successor: a node directly below another node in the hierarchySiblings: nodes that have the same parentAncestors of a node: its parent, the parent of its parent, etc.Descendants of a node: its children, the children of its children, etc.Tree Terminology

12. 10-12Tree TerminologyABCEDFGHNode A is the parent of nodesB, C, D, ENode E is a child of node ANodes B, C, D, Eare siblingsNodes F, B, and A are ancestors of node HNodes F, Gand H are descendantsof node BAll nodes, except A, are descendants of node A

13. 10-13Tree TerminologyLeaf node: a node without childrenInternal node: a node with one of more children

14. 10-14Tree TerminologyLeaf nodes or external nodesRootInterior or internal nodes

15. 10-15DiscussionDoes a leaf node have any children?Does the root node have a parent?How many parents does every node other than the root node have?

16. 10-16Height of a TreeA path is a sequence of edges leading from one node to anotherLength of a path: number of edges on the pathHeight of a (non-empty) tree : length of the longest path from the root to a leafWhat is the height of a tree that has only a root node?

17. 10-17Tree TerminologyRootABFHEJCDILMNGKHeight = 3A pathPath oflength 3

18. 10-18Level of a NodeLevel of a node: number of edges between root and the nodeIt can be defined recursively:Level of root node is 0Level of a node that is not the root node is level of its parent + 1Question: What is the height of a tree in terms of levels?

19. 10-19Level of a NodeLevel 0Level 1Level 2Level 3

20. 10-20SubtreesA subtree of a node consists of a child node and all its descendantsA subtree is itself a treeA node may have many subtrees

21. 10-21SubtreesSubtrees of the node labeled EE

22. 10-22More Tree TerminologyDegree of a node: the number of children it hasDegree of a tree: the maximum of the degrees of the nodes of the tree

23. 10-23DegreeABFHEJCDILMGK4200310010100Degrees of the nodes are indicated beside the nodes

24. 10-24Binary TreesGeneral tree: a tree each of whose nodes may have any number of childrenn-ary tree: a tree each of whose nodes may have no more than n childrenBinary tree: a tree each of whose nodes may have no more than 2 childreni.e. a binary tree is a tree with degree 2The children of a node (if present) are called the left child and right child

25. 10-25Recursive definition of a binary tree:it isthe empty tree, ora tree which has a root whose left and right subtrees are binary treesA binary tree is an ordered tree, i.e. it matters whether a child is a left or right childBinary Trees

26. 10-26Binary TreeAIHDEBFCGLeft child of ARight child of A

27. 10-27Tree TraversalsA traversal of a tree starts at the root and visits each node of the tree once.Common tree traversals:preorderinorderpostorderlevel-order

28. 10-28Preorder TraversalStart at the rootVisit each node, followed by its children; we will visit the left child before the right oneRecursive algorithm for preorder traversal:If tree is not empty,Visit root node of treePerform preorder traversal of its left subtreePerform preorder traversal of its right subtreeWhat is the base case?What is the recursive part?

29. 10-29Preorder Traversalpublic void preorder (BinaryTreeNode<T> r) { if (r != null) { visit(r); preorder (r.getLeftChild()); preorder (r.getRightChild()); }}

30. 10-30AIHDEBFCGPreorder TraversalIn a preorder traversal of this tree the nodes are visited in the order ABDHECFIG

31. 10-31Inorder TraversalStart at the rootVisit the left child of each node, then the node, then any remaining nodesRecursive algorithm for inorder traversalIf tree is not empty,Perform inorder traversal of left subtree of rootVisit root node of treePerform inorder traversal of its right subtree

32. 10-32Inorder Traversalpublic void inorder (BinaryTreeNode<T> r) { if (r != null) { inorder (r.getLeftChild()); visit(r); inorder (r.getRightChild()); }}

33. 10-33AIHDEBFCGIn an inorder traversal of this tree the nodes are visited in the order DHBEAIFCGInorder Traversal

34. 10-34Postorder TraversalStart at the rootVisit the children of each node, then the nodeRecursive algorithm for postorder traversalIf tree is not empty,Perform postorder traversal of left subtree of rootPerform postorder traversal of right subtree of rootVisit root node of tree

35. 10-35Postorder Traversalpublic void postorder (BinaryTreeNode<T> r) { if (r != null) { postorder (r.getLeftChild()); postorder (r.getRightChild()); visit(r); }}

36. 10-36AIHDEBFCGIn an postorder traversal of this tree the nodes are visited in the order HDEBIFGCAPostorder Traversal

37. 10-37Level Order TraversalStart at the rootVisit the nodes at each level, from left to rightIs there a recursive algorithm for a level order traversal?

38. 10-38Level Order TraversalAIHDEBFCGIn a level order traversal of this tree the nodes will be visited in the order ABCDEFGHI

39. 10-39Level Order TraversalWe need to use a queue:Start at the rootVisit the nodes at each level, from left to rightAIHDEBFCGqueue

40. 10-40Level Order TraversalPut A in the queueAIHDEBFCGA

41. 10-41Level Order Traversal1. Remove the first node from the queueAIHDEBFCGA

42. 10-42Level Order Traversal2. Enqueue all neighbours of the node that was removed from the queueAIHDEBFCGAB C

43. 10-43Level Order TraversalRepeat steps 1 and 2 until the queue is emptyAIHDEBFCGA B C

44. 10-44Level Order TraversalAIHDEBFCGA B C D ERepeat steps 1 and 2 until the queue is empty

45. 10-45Level Order TraversalAIHDEBFCGA B C D E F GRepeat steps 1 and 2 until the queue is empty

46. 10-46Level Order TraversalAIHDEBFCGA B C D E F G HRepeat steps 1 and 2 until the queue is empty

47. 10-47Level Order TraversalAIHDEBFCGA B C D E F G HRepeat steps 1 and 2 until the queue is empty

48. 10-48Level Order TraversalAIHDEBFCGA B C D E F G H IRepeat steps 1 and 2 until the queue is empty

49. 10-49Level Order TraversalAIHDEBFCGA B C D E F G H IRepeat steps 1 and 2 until the queue is empty

50. 10-50Level Order TraversalAIHDEBFCGA B C D E F G H IRepeat steps 1 and 2 until the queue is empty

51. 10-51Level Order TraversalAIHDEBFCGLevel order traversal: A B C D E F G H I The queue is empty. The algorithm terminates

52. 10-52Level order TraversalAlgorithm levelOrder (root) {Input: root of a binary treeOutput: Nothing, but visit the nodes of the tree in level order if root = null then return Q = empty queue Q.enqueue(root); while Q is not empty do { v = Q.dequeue(); visit(v); if v.leftChild() != null then Q.enqueue(v.leftChild()); if v.rightChild() != null then Q.enqueue(v.rightChild()); }}

53. 10-53Iterative Binary Tree TraversalsIn recursive tree traversals, the Java execution stack keeps track of where we are in the tree (by means of the activation records for each call)In iterative traversals, the programmer needs to keep track!An iterative traversal uses a container to store references to nodes not yet visitedThe order in which the nodes are visited will depend on the type of container being used (stack, queue, etc.)

54. 10-54An Iterative Traversal Algorithm // Assumption: the tree is not empty Create an empty container to hold references to nodes yet to be visited. Put reference to the root node in the container. While the container is not empty { Remove a reference x from the container. Visit the node x points to. Put references to non-empty children of x in the container.}

55. 10-55Container is a stack: if we push the right child of a node before the left child, we get preorder traversalContainer is a queue: if we enqueue the left child before the right, we get a level order traversalIterative Binary Tree Traversals

56. 10-56Operations on a Binary TreeWhat might we want to do with a binary tree?Add an elementRemove an elementIs the tree empty?Get size of the tree (i.e. how many elements)Traverse the tree (in preorder, inorder, postorder, level order)

57. 10-57Possible Binary Tree Operations OperationDescriptiongetRootReturns a reference to the root of the treeisEmptyDetermines whether the tree is emptysizeDetermines the number of elements in the treefindReturns a reference to the specified target, if foundtoStringReturns a string representation of tree’s contentsiteratorInOrderReturns an iterator for an inorder traversaliteratorPreOrderReturns an iterator for a preorder traversaliteratorPostOrderReturns an iterator for a postorder traversaliteratorLevelOrderReturns an iterator for a levelorder traversal

58. 9-582-58What is an Iterator?An iterator is an abstract data type that allows us to iterate through the elements of a collection one by oneOperationsnext: next element of the collection; ERROR if the element does not existhasNext: true if there are more elements in the collection; false otherwiseremove: removes the last element returned by the iterator

59. 9-592-59Iterator Interfacepublic interface Iterator<T> {public boolean hasNext( );public T next( );public void remove( ); // (optional operation)}This interface is in the java.util package of Java

60. Binary Tree ADTpackage binaryTree;import java.util.Iterator;public interface BinaryTreeADT<T> { public T getRoot (); public boolean isEmpty(); public int size(); public T find (T targetElement) throws ElementNotFoundException; public String toString(); public Iterator<T> iteratorInOrder(); public Iterator<T> iteratorPreOrder(); public Iterator<T> iteratorPostOrder(); public Iterator<T> iteratorLevelOrder();}10-60

61. 10-61Linked Binary Tree ImplementationTo represent the binary tree, we will use a linked structure of nodesroot: reference to the node that is the root of the treecount: keeps track of the number of nodes in the treeFirst, how will we represent a node of a binary tree?

62. 10-62Linked Binary Tree ImplementationA binary tree node will contain a reference to a data element references to its left and right children and to its parentleft and right children are binary tree nodes themselves

63. 10-63BinaryTreeNode classRepresents a node in a binary treeAttributes:element: reference to data element left: reference to left child of the noderight: reference to right child of the nodeparent: reference to the parent of the node

64. 10-64A BinaryTreeNode Objectprotected T element;protected BinaryTreeNode<T> left, right, parent;Note that either or both of the left and right references could be nullWhat is the meaning of protected?

65. 10-65LinkedBinaryTree ClassAttributes: protected BinaryTreeNode<T> root; protected int count;The attributes are protected so that they can be accessed directly in any subclass of the LinkedBinaryTree class

66. 10-66LinkedBinaryTree ClassConstructors: //Creates empty binary tree public LinkedBinaryTree() { count = 0; root = null; } //Creates binary tree with specified element as its root public LinkedBinaryTree (T element) { count = 1; root = new BinaryTreeNode<T> (element); }

67. 10-67/* Returns a reference to the specified target element if it is found in this binary tree.Throws an ElementNotFoundException if not found. */ public T find(T targetElement) throws ElementNotFoundException { BinaryTreeNode<T> current = findAgain( targetElement, root ); if ( current == null ) throw new ElementNotFoundException("binary tree"); return (current.element); }

68. 10-68DiscussionWhat is element in this statement from the method? return (current.element);If element were private rather than protected in BinaryTreeNode.java, what would be need in order to access it?We will now look at the helper method findAgain …

69. 10-69private BinaryTreeNode<T> findAgain(T targetElement, BinaryTreeNode<T> next) { if (next == null) return null; if (next.element.equals(targetElement)) return next; BinaryTreeNode<T> temp = findAgain(targetElement, next.left); if (temp == null) temp = findAgain(targetElement, next.right); return temp; }

70. 10-70DiscussionWhat kind of method is findAgain?What is the base case?There are two!What is the recursive part?

71. 10-71/* Performs an inorder traversal on this binary tree by calling a recursive inorder method that starts with the root.Returns an inorder iterator over this binary tree */ public Iterator<T> iteratorInOrder() { ArrayUnorderedList<T> tempList = new ArrayUnorderedList<T>(); inorder (root, tempList); return tempList.iterator(); }

72. 10-72DiscussioniteratorInOrder returns an iterator objectIt will perform the iteration in inorderBut where is that iterator coming from? return tempList.iterator();Let’s now look at the helper method inorder …

73. 10-73/* Performs a recursive inorder traversal. Parameters are: the node to be used as the root for this traversal, the temporary list for use in this traversal */ protected void inorder (BinaryTreeNode<T> node, ArrayUnorderedList<T> tempList) { if (node != null) { inorder (node.left, tempList); tempList.addToRear(node.element); inorder (node.right, tempList); } }

74. 10-74DiscussionRecall the recursive algorithm for inorder traversal:If tree is not empty,Perform inorder traversal of left subtree of rootVisit root node of treePerform inorder traversal of its right subtreeThat is exactly the order that is being implemented here!What is “visiting” the root node here?

75. 10-75DiscussionThe data elements of the tree (i.e. items of type T) are being temporarily added to an unordered list, in inorder orderWhy use an unordered list??Why not? We already have this collection, with its iterator operation that we can use!

76. 10-76Using Binary Trees: Expression TreesPrograms that manipulate or evaluate arithmetic expressions can use binary trees to hold the expressionsAn expression tree represents an arithmetic expression such as(5 – 3) * 4 + 9 / 2Root node and interior nodes contain operationsLeaf nodes contain operands

77. 10-77Example: An Expression Tree/-35+ (5 – 3) * 4 + 9 / 24*92

78. 10-78Evaluating Expression TreesWe can use an expression tree to evaluate an expressionWe start the evaluation at the bottom leftWhat kind of traversal is this?

79. 10-79Evaluating an Expression Tree-578/29*This tree represents the expression(9 / 2 + 7) * (8 – 5)Evaluation is based on a postorder traversal:If root node is a leaf, return the associated value.Recursively evaluate expression in left subtree.Recursively evaluate expression in right subtree.Perform operation in root node on these two values, and return result.+

80. 10-80Evaluating an Expression Tree-578/29*+

81. 10-81Evaluating an Expression Tree-578/29*+9/2 = 4.5

82. 10-82Evaluating an Expression Tree-578/29*+4.54.5 + 7 = 11.5

83. 10-83Evaluating an Expression Tree-578/29*+4.511.58 – 5 = 3

84. 10-84Evaluating an Expression Tree-578/29*+4.511.5311.5 * 3 = 34.5

85. 10-85Optional Notes: Building an Expression TreeNow we know how to evaluate an expression represented by an expression treeBut, how do we build an expression tree?We will build it from the postfix form of the expressionExercise: develop the algorithm by following the diagrams on the next pages

86. 10-86Building an Expression TreeThe algorithm will use a stack of ExpressionTree objectsAn ExpressionTree is a special case of a binary treeThe ExpressionTree constructor has 3 parameters:Reference to data itemReference to left childReference to right childThat's all you need to know to develop the algorithm!

87. 10-87Build an expression tree from the postfix expression 5 3 - 4 * 9 +Symbol5push(new ExpressionTree(5,null,null));Processing Step(s)Expression Tree Stack (top at right)5Symbol3push(new ExpressionTree(3,null,null));Processing Step(s)Expression Tree Stack (top at right)53

88. 10-88Symbol-op2 = popop1 = poppush(new ExpressionTree(-,op1,op2));Processing Step(s)Expression Tree Stack (top at right)5-3

89. 10-89Symbol4push(new ExpressionTree(4,null,null));Processing Step(s)Expression Tree Stack (top at right)5-34

90. 10-90Symbol*op2 = popop1 = poppush(new ExpressionTree(*,op1,op2));Processing Step(s)Expression Tree Stack (top at right)5-34*

91. 10-91Symbol9push(new ExpressionTree(9,null,null));Processing Step(s)Expression Tree Stack (top at right)5-34*9

92. 10-92Symbol+op2 = popop1 = poppush(new ExpressionTree(+,op1,op2));Processing Step(s)Expression Tree Stack (top at right)5-34*9+End of the expression has been reached, and the full expression tree is the only tree left on the stack