Trees Briana B. Morrison Adapted from Alan Eugenio
Binary Trees 2 Topics Trees Binary Trees Definitions (full, complete, etc.) Expression Trees Traversals Implementation
Binary Trees 3 Tree Structures
Binary Trees 4 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 SalesR&DManufacturing LaptopsDesktops US International EuropeAsiaCanada
Binary Trees 5
6 Terminology First let’s learn some terminology about trees…
Binary Trees 7
8 Tree Structures
Binary Trees 9
10 Tree Structures
Binary Trees 11
Binary Trees 12
Binary Trees 13
Binary Trees 14 Tree Structures
Binary Trees 15
Binary Trees 16
Binary Trees 17 50, 80, 90, 84
Binary Trees 18 BINARY TREES
Binary Trees 19 Binary Tree Definition A binary tree T is a finite set of nodes with one of the following properties: (a) T is a tree if the set of nodes is empty. (An empty tree is a tree.) (b) The set consists of a root, R, and exactly two distinct binary trees, the left subtree T L and the right subtreeT R. The nodes in T consist of node R and all the nodes in T L and T R.
Binary Trees 20
Binary Trees 21 Binary Tree A binary tree is a tree with the following properties: Each internal node has two children 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 FG D E H I
Binary Trees 22 Examples of Binary Trees Expression tree Non-leaf (internal) nodes contain operators Leaf nodes contain operands Huffman tree Represents Huffman codes for characters appearing in a file or stream Huffman code may use different numbers of bits to encode different characters ASCII or Unicode uses a fixed number of bits for each character
Binary Trees 23 Examples of Huffman Tree Code for b = Code for w = Code for s = 0011 Code for e = 010
Binary Trees 24
Binary Trees 25 HOW CAN WE DEFINE leaves(t), THE NUMBER OF LEAVES IN THE BINARY TREE t? RECURSIVELY!
Binary Trees 26
Binary Trees 27
Binary Trees 28
Binary Trees 29
Binary Trees 30
Binary Trees 31
Binary Trees 32
Binary Trees 33 height(t) = ? To distinguish the height of an empty tree from the height of a single-item tree, What should the height of an empty tree be?
Binary Trees 34
Binary Trees 35
Binary Trees 36
Binary Trees 37 Tree Node Level and Path Length
Binary Trees 38 Depth Example Depth 0 (root) Depth 1 Depth 2
Binary Trees 39
Binary Trees 40
Binary Trees 41
Binary Trees 42
Binary Trees 43
Binary Trees 44
Binary Trees 45
Binary Trees 46
Binary Trees 47
Binary Trees 48
Binary Trees 49 Tree Node Level and Path Length – Depth Discussion Is this tree complete? Is it full?
Binary Trees 50
Binary Trees 51 Tree Node Level and Path Length – Depth Discussion Is this tree complete? Is it full? What is its height?
Binary Trees 52 Tree Node Level and Path Length – Depth Discussion Is this tree complete? Is it full? What is its height?
Binary Trees 53
Binary Trees 54 ABCDERSFGL THIS ASSOCIATION SUGGESTS THAT A COMPLETE BINARY TREE CAN BE STORED IN AN ARRAY:
Binary Trees 55
Binary Trees 56 Children(i) = 2i + 1 and 2i + 2
Binary Trees 57 Parent(i) = (i – 1) / 2
Binary Trees 58
Binary Trees 59
Binary Trees 60 Selected Samples of Binary Trees
Binary Trees 61 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 a1 3b
Binary Trees 62 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? How about coffee?On expense account? StarbucksSpike’sAl FornoCafé Paragon Yes No YesNoYesNo
Binary Trees 63 TRAVERSALS OF A BINARY TREE
Binary Trees 64
Binary Trees 65
Binary Trees 66 ANSWER: 12, 30, 40, 50, 86, 90, 100
Binary Trees 67 Print Arithmetic Expressions Specialization of an inorder traversal print operand or operator when visiting node print “(“ before traversing left subtree print “)“ after traversing right subtree Algorithm printExpression(v) if isInternal (v) print( “(’’ ) inOrder (leftChild (v)) print(v.element ()) if isInternal (v) inOrder (rightChild (v)) print ( “)’’ ) 2 a1 3b ((2 ( a 1)) (3 b))
Binary Trees 68
Binary Trees 69 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) cs16/ homeworks/ todo.txt 1K programs/ DDR.java 10K Stocks.java 25K h1c.doc 3K h1nc.doc 2K Robot.java 20K
Binary Trees 70
Binary Trees 71
Binary Trees 72 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 isExternal (v) return v.element () else x evalExpr(leftChild (v)) y evalExpr(rightChild (v)) operator stored at v return x y
Binary Trees 73
Binary Trees 74 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 Make Money Fast! 1. MotivationsReferences2. Methods 2.1 Stock Fraud 2.2 Ponzi Scheme 1.1 Greed1.2 Avidity 2.3 Bank Robbery Algorithm preOrder(v) visit(v) for each child w of v preorder (w)
Binary Trees 75
Binary Trees 76
Binary Trees 77 Binary Tree Traversals Preorder: Visit root, traverse left, traverse right Inorder: Traverse left, visit root, traverse right Postorder: Traverse left, traverse right, visit root
Binary Trees 78 Visualizing Tree Traversals Can visualize traversal by imagining a mouse that walks along outside the tree If mouse keeps the tree on its left, it traces a route called the Euler tour: Preorder: record node first time mouse is there Inorder: record after mouse traverses left subtree Postorder: record node last time mouse is there
Binary Trees 79 Visualizing Tree Traversals (2) Preorder: a, b, d, g, e, h, c, f, i, j
Binary Trees 80 Visualizing Tree Traversals (3) Inorder: d, g, b, h, e, a, i, f, j, c
Binary Trees 81 Visualizing Tree Traversals (4) Postorder: g, d, h, e, b, i, j, f, c, a
Binary Trees 82 Traversals of Expression Trees Inorder traversal can insert parentheses where they belong for infix form Postorder traversal results in postfix form Prefix traversal results in prefix form Infix form (x + y) * ((a + b) / c) Postfix form: x y + a b + c / * Prefix form: * + x y / + a b c
Binary Trees 83
Binary Trees 84 ANSWER: A, B, C, D, E, R, S, F, G, L
Binary Trees 85 Implementation of Level-Order What data structures would you need?
Binary Trees 86
Binary Trees 87
Binary Trees 88 Binary Tree Nodes
Binary Trees 89 The BTNode Class Like linked list, a node has data + links to successors Data is reference to object of type E Binary tree node has links for left and right subtrees
Binary Trees 90 The Binary_Tree Class
Binary Trees 91 General Trees Implementations of Ordered Trees Multiple links first_child and next_sibling links Correspondence with binary trees
Binary Trees 92 Linked Implementation
Binary Trees 93 Rotated Form first_child (left) links: black next_sibling (right) links: red
Binary Trees 94 General (Non-Binary) Trees Nodes can have any number of children
Binary Trees 95 General (Non-Binary) Trees (2) A general tree can be represented using a binary tree Left link is to first child Right link is to next younger sibling
Binary Trees 96 Summary Slide 1 §- trees -hierarchical structures that place 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 may have multiple successors at the next level. Hence a tree is a non-linear structure. -Tree terminology with which you should be familiar: parent | child | descendents | leaf node | interior node | subtree.
Binary Trees 97 subtree 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. A B DC GH E F IJ K Subtree: tree consisting of a node and its descendants
Binary Trees 98 Summary Slide 2 §- Binary Trees -Most effective as a storage structure if it has high density §-ie: data are located on relatively short paths from the root. §-A complete binary tree has the highest possible density -an n-node complete binary tree has depth int(log 2 n). -At the other extreme, a degenerate binary tree is equivalent to a linked list and exhibits O(n) access times.
Binary Trees 99 Summary Slide 3 §- Traversing Through a Tree -There are six simple recursive algorithms for tree traversal. -The most commonly used ones are: 1)inorder (LNR) 2)postorder (LRN) 3)preorder (NLR). -Another technique is to move left to right from level to level. §-This algorithm is iterative, and its implementation involves using a queue.