1 / 89

Binary Trees

Binary Trees. Tree Example. Tree Structures. A tree is a hierarchical structure that places elements in nodes along branches that originate from a root . Nodes in a tree are subdivided into levels in which the topmost level holds the root node.

paul-rich
Download Presentation

Binary Trees

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

  2. Tree Example

  3. Tree Structures • A tree is a hierarchical structure that places elements in nodes along branches that originate from a root. • Nodes in a tree are subdivided into levels in which the topmost level holds the root node. • Any node in a tree can have multiple successors at the next level • Therefore a tree is a nonlinear structure.

  4. Tree Structures (continued) • Operating systems use a general tree to maintain file structures.

  5. Tree Terminology • Tree structure • Collection of nodesthat originate from a unique starting node called the root. • Each node consists of a value and a set of zero or more links to successor nodes. • The terms parent and child describe the relationship between a node and any of its successor nodes.

  6. Tree Terminology (continued) s

  7. Tree Terminology (continued) • Consists of nodes connected by edges • A tree is an instance of a more general category called a graph(a later slideshow discusses graphs) Nodes Edges Nodes connected by edges (a graph – but not a tree)

  8. Tree Terminology • Tree – recursively defined as empty or a root node with zero or more sub-trees • Node – a holder for data plus edges to children • Edge – connects a parent node to a child node • Root – a pointer to the first node, if it exists, or NULL • Leaf node – a node with no children • Internal node – a node with one or two children • Path – sequence of edges between two nodes • Height – longest path in a tree from root to any other node • Depth – number of edges from root to a node

  9. Tree Terminology (continued) • A path between a parent node P and any node N in its subtree is a sequence of nodes • P=X0, X1, . . ., Xk = N • k is the length of the path • Each node Xi in the sequence is the parent of Xi+1 for 0  i  k-1. • Depth (also called Level) of a node • Length of the path from root to the node. • Equivalent - number of edges from root to the node. • Viewing a node as a root of its subtree, the height of a node is the length of the longest path from the node to a leaf in the subtree. • The height of a tree is the maximum level in the tree.

  10. Tree Terminology (continued) Height = 3

  11. Sorted Binary Trees • In a binary tree, each parent has no more than two children • each node (item in the tree) has a value • a total order (linear order) is defined on these values • left subtree of a node contains only values less than the node's value • right subtree contains only values greater than or equal to the node's value. 21 10 34 5 25 39 2 7 33

  12. Binary Trees • A compiler builds unsorted binary trees while parsing expressions in a program's source code.

  13. Binary Trees (continued) • Each node of a binary tree defines a left and a right subtree. Each subtree is itself a tree. Right child of T Left child of T

  14. Binary Trees (continued) • A recursive definition of a binary tree: • T is a binary tree if T • has no node (T is an empty tree) or • has at most two subtrees.

  15. { -1 if TN is empty 1+max( height(TL), height(TR)) if TN not empty height(N) = height(TN) = Height of a Binary Tree • The height of a binary tree is the length of the longest path from the root to a leaf node • Let TN be the subtree with root N and TL and TR be the roots of the left and right subtrees of N. Then leaf node will always have a height of 0

  16. Height of a Binary Tree (concluded) Degenerate binary tree (least dense)

  17. Density of a Binary Tree • In a binary trees, the number of nodes at each level falls within a range of values. • At level 0, there is 1 node, the root; at level 1 there can be 1 or 2 nodes. • At any level k, the number of nodes is in the range from 1 to 2k. • The number of nodes per level contributes to the density of the tree. • Intuitively, density is a measure of the size of a tree (number of nodes) relative to the height of the tree.

  18. Density of a Binary Tree (continued)

  19. Density of Binary Tree • If degenerate trees allowed: • Problem – search in basic binary tree is O(N) • Value could be anywhere in tree • No better than a list

  20. Density of a Binary Tree (continued) • A complete binary tree of height h has all possible nodes through level h-1, and the nodes on depth h exist left to right with no gaps • Complete binary trees are excellent storage structures due to packing a large number of nodes near the root

  21. Density of a Binary Tree (continued)

  22. Density of a Binary Tree (continued) • Determine the minimum height of a complete tree that holds n elements. • Through first h - 1 levels, total number of nodes is 1 + 2 + 4 + ... + 2h-1 = 2h - 1 • At depth h, the number of additional nodes ranges from a minimum of 1 to a maximum of 2h. • Hence the number of nodes n in a complete binary tree of height h ranges between2h - 1 + 1 = 2h n  2h - 1 + 2h = 2h+1 - 1 < 2h+1

  23. Density of a Complete Binary Tree • After applying the logarithm base 2 to all terms in the inequality, we have h  log2 n < h+1 and conclude that a completebinary tree with n nodes must have height h = int(log2n) search in complete binary tree is O(log2(n))

  24. Binary Tree Nodes • Define a binary tree a node as an instance of the generic TNode class. • A node contains three fields. • The data value, called nodeValue. • The reference variables, left and right that identify the left child and the right child of the node respectively.

  25. Binary Tree Nodes (continued) • The TNode class allows us to constructa binary tree as a collection of TNode objects.

  26. TNode Class // declared as an inner class within the class building the tree

  27. Building a Binary Tree Using previous slide’s TNode class

  28. Scanning a Binary Tree • Next issue: • How will you retrieve the data stored in the tree?

  29. Iterative Level-Order Scan • A level-order scan visits the root, then nodes on level 1, then nodes on level 2, etc.

  30. Iterative Level-Order Scan • A level-order scan is an iterative process that uses a queue as an intermediate storage collection. • Initially, the root enters the queue. • Start a loop ending when the queue is empty • Remove a node from the queue • Perform some action with the node • Add its children onto the queue • Because siblings enter the queue during a visit of their parent, the siblings (on the same level) will exit the queue in successive iterations.Notice in the next example how I'm using Java's Queue interface

  31. Iterative Level-Order Scan (continued)

  32. Iterative Level-Order Scan (continued) Step 1: remove A then add B and C into queue Step 2: remove B then add D into the queue Step 3: remove C then add E into the queue Step 4: remove D Step 5: remove E

  33. Iterative Level-Order Scan (continued) A remove A B C C D remove B D E F remove C E F G H remove D F G H remove E G H I remove F H I remove G I J remove H J remove I remove J Notice the order removed from queue and appended to the output s

  34. Recursive Binary Tree-Scan Algorithms • If current node == null is stopping condition • To scan a tree recursively • Visit and display the node (D) • scan the left subtree (L) and scan the right subtree (R) • The order in which you perform the D, L, R tasks determines the order in which nodes are retrieved • In the following code, t is initially the reference to the root node:

  35. Inorder Scan L D R inorderDisplay method call stack: inorderDisplay(a) inorderDisplay(b) inorderDisplay(d) inorderDisplay(g) inorderDisplay(null) append g to s inorderDisplay(null) append d to s inorderDisplay(h) inorderDisplay(j) inorderDisplay(null) append j to s inorderDisplay(null) append h to s inorderDisplay(null) append b to s inorderDisplay(null) append a to s inorderDisplay(c) inorderDisplay(e) inorderDisplay(null) append e to s inorderDisplay(null) append c to s inorderDisplay(f) inorderDisplay(null) append f to s inorderDisplay(i) inorderDisplay(null) append i to s inorderDisplay(null) • Scan is in order of visits to the left subtree, the node's own value, and visits to the right subtree Inorder Scan: G D J H B A E C F I

  36. Postorder Scan L R D • Scan is in order of visits to the left subtree, visits to the right subtree, and the node's own value Scan order: G J H D B E I F C A Can you write the method call stack for this?

  37. Method Call Stack for Postorder inorderDisplay method call stack: inorderDisplay(a) inorderDisplay(b) inorderDisplay(d) inorderDisplay(g) inorderDisplay(null) inorderDisplay(null) append g to s inorderDisplay(h); inorderDisplay(j); inorderDisplay(null); inorderDisplay(null); append j to s inorderDisplay(null); append h to s // rest left to you… Scan order: G J H D B E I F C A

  38. Preorder Scan D L R • Scan is in order of the node's own value, visits to the left subtree, and visits to the right subtree Scan order: A B D G H J C E F I

  39. More Recursive Scanning Examples Preorder (NLR): A B D G C E H I F Inorder (LNR): D G B A H E I C F Postorder (LRN): G D B H I E F C A

  40. Visitor Design Pattern • When an action is needed on each element of a collection • Don't know in advance what the type of each element will be • Defines the visit() method which denotes what a visitor does • For a specific visitor pattern • Create a Visitor interface • Create a class that implements the Visitor interface • In class scanning a tree • Create an object of the class implementing the Visitor interface • During traversal, call Visitor object's visit() and pass the current value as an argument

  41. Visitor Design Pattern (continued) 1. 2. Another possibility (requires T to be "Comparable"): 2.

  42. 3. scanInorder() • This recursive method scanInorder()provides a generalized inorder traversal of a tree that performs an action specified by a visitor pattern. Uses Visitor object's visit instead of System.out.println

  43. scanInOrder() • If Visitor parameter is VisitorOutput • Prints output to the console • If Visitor parameter is VisitMax • VisitMax parameter stores the tree element with the max value after scanInOrder finishes

  44. Program B_Tree • Illustrates use of all the scanning methods

  45. Computing Tree Height • Recall that the height of a binary tree can be computed recursively. { -1 if T is empty height(T) = 1 + max(height(TL), height(TR)) if T is nonempty F

  46. Computing Tree Height (continued)

  47. Copying a Binary Tree • Simple case – exact duplicate • Duplicate with additional information • Contain nodes with additional field • Possibility - references the parent - this allows a scan up the tree along the path of parents

  48. Copying a Binary Tree (continued) • Copy a tree using a postorder scan • Build the duplicate tree from the bottom up.

  49. Clearing a Binary Tree • Clear a tree with a postorder scan • Remove the left and right subtrees before removing the node.

More Related