Tree Data Structure

35
Trees and Binary Trees Become Rich Force Others to be Poor Rob Banks Stock Fraud The class notes are a compilation and edition from many source does not claim intellectual property or ownership of the lectu

description

Introduction to Tree Data Structure.

Transcript of Tree Data Structure

  • Trees and Binary TreesBecome RichForce Others to be PoorRob BanksStockFraudThe class notes are a compilation and edition from many sources. The instructor does not claim intellectual property or ownership of the lecture notes.

  • Nature View of a Treebranchesleavesroot

  • Computer Scientists Viewbranchesleaves

  • What is a TreeA tree is a finite nonempty set of elements.It is an abstract model of a hierarchical structure.consists of nodes with a parent-child relation.Applications:Organization chartsFile systemsProgramming environments

  • Tree TerminologyRoot: node without parent (A)Siblings: nodes share the same parentInternal node: node with at least one child (A, B, C, F)External node (leaf ): node without children (E, I, J, K, G, H, D)Ancestors of a node: parent, grandparent, grand-grandparent, etc.Descendant of a node: child, grandchild, grand-grandchild, etc.Depth of a node: number of ancestorsHeight of a tree: maximum depth of any node (3)Degree of a node: the number of its childrenDegree of a tree: the maximum number of its node.

    subtreeSubtree: tree consisting of a node and its descendants

  • Tree PropertiesPropertyValueNumber of nodesHeightRoot NodeLeavesInterior nodesAncestors of HDescendants of BSiblings of ERight subtree of ADegree of this tree

  • Tree ADTWe use positions to abstract nodesGeneric methods:integer size()boolean isEmpty()objectIterator elements()positionIterator positions()Accessor methods:position root()position parent(p)positionIterator children(p)Query methods:boolean isInternal(p)boolean isExternal(p)boolean isRoot(p)Update methods:swapElements(p, q)object replaceElement(p, o)Additional update methods may be defined by data structures implementing the Tree ADT

  • Intuitive Representation of Tree NodeList Representation( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) )The root comes first, followed by a list of links to sub-treesHow many link fields are needed in such a representation?

  • TreesEvery tree node:object useful informationchildren pointers to its children

  • A Tree RepresentationA node is represented by an object storingElementParent nodeSequence of children nodes

  • Left Child, Right Sibling Representation

  • Tree TraversalTwo main methods:PreorderPostorderRecursive definition

    Preorder: visit the roottraverse in preorder the children (subtrees)

    Postordertraverse in postorder the children (subtrees)visit the root

  • Preorder TraversalA traversal visits the nodes of a tree in a systematic mannerIn a preorder traversal, a node is visited before its descendants Application: print a structured documentAlgorithm preOrder(v)visit(v)for each child w of vpreorder (w)

  • Postorder TraversalIn a postorder traversal, a node is visited after its descendantsApplication: compute space used by files in a directory and its subdirectoriesAlgorithm postOrder(v)for each child w of vpostOrder (w)visit(v)

  • Binary TreeA binary tree is a tree with the following properties:Each internal node has at most two children (degree of two)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 eithera tree consisting of a single node, ORa tree whose root has an ordered pair of children, each of which is a binary treeApplications:arithmetic expressionsdecision processessearchingABCFGDEHI

  • BinaryTree ADTThe BinaryTree ADT extends the Tree ADT, i.e., it inherits all the methods of the Tree ADTAdditional methods:position leftChild(p)position rightChild(p)position sibling(p)Update methods may be defined by data structures implementing the BinaryTree ADT

  • Examples of the Binary Tree

  • Differences Between A Tree and A Binary TreeThe subtrees of a binary tree are ordered; those of a tree are not ordered.Are different when viewed as binary trees.Are the same when viewed as trees.

  • Data Structure for Binary TreesA node is represented by an object storingElementParent nodeLeft child nodeRight child node

  • Arithmetic Expression TreeBinary tree associated with an arithmetic expressioninternal nodes: operatorsexternal nodes: operandsExample: arithmetic expression tree for the expression (2 (a - 1) + (3 b))

  • Decision TreeBinary tree associated with a decision processinternal nodes: questions with yes/no answerexternal nodes: decisionsExample: dining decisionWant a fast meal?How about coffee?On expense account?StarbucksSpikesAl FornoCaf ParagonYesNoYesNoYesNo

  • Maximum Number of Nodes in a Binary TreeThe maximum number of nodes on depth i of a binary tree is 2i, i>=0.

    The maximum nubmer of nodes in a binary tree of height k is 2k+1-1, k>=0.Prove by induction.

  • Relations between Number ofLeaf Nodes and Nodes of Degree 2 For any nonempty binary tree, T, if n0 is the number of leaf nodes and n2 the number of nodes of degree 2, then n0=n2+1

    PROOF: Let n and B denote the total number of nodes and branches in T. Let n0, n1, n2 represent the nodes with no children, single child, and two children respectively. B+1=n B=n1+2n2 n=n0+n1+n2 n1+2n2+1= n n0=n2+1

  • Full Binary TreeA full binary tree of a given height k has 2k+11 nodes.

  • Labeling Nodes In A Full Binary TreeLabel the nodes 1 through 2k+1 1. Label by levels from top to bottom.Within a level, label from left to right.123456789101112131415

  • Node Number Properties Parent of node i is node i / 2, unless i = 1.Node 1 is the root and has no parent.

  • Node Number Properties Left child of node i is node 2i, unless 2i > n, where n is the number of nodes.If 2i > n, node i has no left child.

  • Node Number Properties Right child of node i is node 2i+1, unless 2i+1 > n, where n is the number of nodes.If 2i+1 > n, node i has no right child.

  • Complete Binary TreesA labeled binary tree containing the labels 1 to n with root 1, branches leading to nodes labeled 2 and 3, branches from these leading to 4, 5 and 6, 7, respectively, and so on.A binary tree with n nodes and level k is complete iff its nodes correspond to the nodes numbered from 1 to n in the full binary tree of level k.

  • Binary Tree TraversalsLet l, R, and r stand for moving left, visiting the node, and moving right.

    There are six possible combinations of traversallRr, lrR, Rlr, Rrl, rRl, rlR

    Adopt convention that we traverse left before right, only 3 traversals remainlRr, lrR, Rlrinorder, postorder, preorder

  • Inorder TraversalIn an inorder traversal a node is visited after its left subtree and before its right subtreeAlgorithm inOrder(v)if isInternal (v)inOrder (leftChild (v))visit(v)if isInternal (v)inOrder (rightChild (v))

  • Print Arithmetic ExpressionsSpecialization of an inorder traversalprint operand or operator when visiting nodeprint ( before traversing left subtreeprint ) after traversing right subtreeAlgorithm inOrder (v)if isInternal (v){ print(()inOrder (leftChild (v))}print(v.element ())if isInternal (v){inOrder (rightChild (v))print ())}((2 (a - 1)) + (3 b))

  • Evaluate Arithmetic Expressionsrecursive method returning the value of a subtreewhen visiting an internal node, combine the values of the subtreesAlgorithm evalExpr(v)if isExternal (v)return v.element ()elsex evalExpr(leftChild (v))y evalExpr(rightChild (v)) operator stored at vreturn x y

  • Creativity: pathLength(tree) = depth(v) v treeAlgorithm pathLength(v, n)Input: a tree node v and an initial value nOutput: the pathLength of the tree with root vUsage: pl = pathLength(root, 0);

    if isExternal (v)return nreturn (pathLength(leftChild (v), n + 1) +pathLength(rightChild (v), n + 1) + n)

  • Euler Tour TraversalGeneric traversal of a binary treeIncludes a special cases the preorder, postorder and inorder traversalsWalk around the tree and visit each node three times:on the left (preorder)from below (inorder)on the right (postorder)

  • Euler Tour TraversaleulerTour(node v) { perform action for visiting node on the left; if v is internal then eulerTour(v->left); perform action for visiting node from below; if v is internal then eulerTour(v->right); perform action for visiting node on the right;}