1 / 52

TREES

TREES. Linked Lists vs Trees. With large amounts of data, access time for linked lists is quite long. Access time can be improved with trees - Linked List : O (n) - Binary Tree : O (square root of n) - Binary Search Tree : O (log n). Definition. The Tree Data Structure

Download Presentation

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

  2. Linked Lists vs Trees • With large amounts of data, access time for linked lists is quite long. • Access time can be improved with trees - Linked List : O (n)- Binary Tree : O (square root of n)- Binary Search Tree : O (log n)

  3. Definition • The Tree Data Structure • stores objects (nodes) hierarchically • nodes have parent-child relationships • operations include accessing the parent or children of a given node • A tree T is a set of nodes such that • there is a distinguished node r (called the root) of T that has no parent • each node v of T except r has a parent node

  4. Visualizing a Tree R Root Child T O I P A M N G

  5. Sample Uses • A company’s organizational structure • Family tree • The Java class hierarchy • O/S directory structure • Book (parts, chapters, sections) • Arithmetic expressions • Web page links (?)

  6. Tree Terminology • Root • the only node that has no parent • Leaf (External node) • node that has no children • Internal node • node that has at least one child • Siblings • nodes that have a common parent

  7. More Tree Terminology • Ancestor • recursive definition: ancestors of a node v are v itself and the ancestors of its parent • proper ancestors: ancestors excluding itself • Descendant • v is a descendant of u if u is an ancestor of v • Subtree of T rooted at v • set of all descendants of v

  8. Even More Terminology • Ordered Tree • children of a node have a strict linear order • Binary Tree • an ordered tree where nodes have at most two children (left and right) • Depth and Height of a node • depth: distance from node to root • height: from node to its farthest descendant

  9. Tree ADT • Tree-specific operations • retrieval: root(), parent(v), children(v) • test: isInternal(v), isExternal(v), isRoot(v) • Container-specific operations • Tree ADT is just a special type of container • methods: size(), isEmpty(), replace(v,e), etc.

  10. root() parent(v) Return the root of T; error if tree is empty Input: None Output: Position (Node) Return the parent of v; error if v = root() Input: Position Output: Position Tree Operations

  11. children(v) isInternal(v) Return children of v Input: Position Output: Enumeration of Positions Test whether position v is internal Input: Position Output: boolean More Tree Operations

  12. isExternal(v) isRoot(v) Test whether position v is external Input: Position Output: boolean Test whether position v is the root Input: Position Output: boolean More Tree Operations

  13. Container-Specific Operations • size(): returns number of nodes/positions • isEmpty(): test for empty tree • positions(): returns all positions • elements(): returns all objects/elements • swap(v,w): swaps elements of 2 positions • replace(v,e): assigns element to position

  14. Tree Implementation • Sequence/Array-based implementation • elements (or references to them) are stored in an array • parent-child relationships derived from indices • Linked implementation • elements stored in nodes • nodes contain pointers to parent and children

  15. Algorithms on Trees • Depth computation • Height computation • node height • tree height • Traversals • preorder • postorder

  16. Computing Depth Algorithm depth(v) Input: Node v Output: Integer if isRoot(v) return 0 else return 1 + depth(parent(v))

  17. Computing Node Height Algorithm height(v) Input: Node v Output: Integer if isExternal(v) // leaf nodes have 0 height return 0 else m  max[height(w)] where w is a child of v return 1 + m

  18. Computing Tree Height • Method 1 • compute the depths of all the leaves • get the maximum • Method 2 • compute height of root recursively • height of a node is one plus the maximum height of the subtrees rooted at its children • heights of subtrees rooted at leaves: 0

  19. Traversals • Traversal • systematic way of accessing or visiting the nodes of a tree • Preorder • visit root first, then traverse its subtrees (recursive) • Postorder • visit subtrees first, then root (recursive)

  20. Preorder Traversal Algorithm preorder(v) Input: Node v Output: Depends on application perform the “visit” action for node v // example: print element(v) for each child w of v do preorder(w)

  21. Postorder Traversal Algorithm postorder(v) Input: Node v Output: Depends on application for each child w of v do postorder(w) perform the “visit” action for node v // example: print element(v)

  22. Traversals - Query • Given the following tree, show (by arrows) a preorder and a post-order traversal.

  23. Traversals-Query Paper Title Abstract Chap 1 Chap 2 Chap 3 References Chap 1.1 Chap 1.2 Chap 2.1 Chap 2.2 Chap 2.3 Chap 3.1 Chap 3.2

  24. Traversals-Pre-Order Paper Title Abstract Chap 1 Chap 2 Chap 3 References Chap 1.1 Chap 1.2 Chap 2.1 Chap 2.2 Chap 2.3 Chap 3.1 Chap 3.2

  25. Traversals-Post-Order Paper Paper Title Abstract Chap 1 Chap 2 Chap 3 References Chap 1.1 Chap 1.2 Chap 2.1 Chap 2.2 Chap 2.3 Chap 3.1 Chap 3.2

  26. Binary Trees • Definition - A binary tree is a tree in which no nodes can have more than two children • - average depth is O (square root of n) • - special tree, binary search tree has an average depth of O (log n)

  27. Binary Tree Properties Given a binary tree with n nodes, i internal nodes, e external nodes and height h: • h+1 <= e <= 2h • h <= i <= 2h -1 • 2h +1 <= n <= 2h+1 -1 • log(n+1) -1 <= h <= (n-1)/2(Minimum height is O(log n))

  28. leftChild(v) rightChild(v) Return the left child of v; error if external Input: Position Output: Position Return the right child of v; error if external Input: Position Output: Position Binary Tree access methods

  29. expandExternal(v) removeAboveExternal(v) Create two nodes under node v; error if internal Remove parent of v including its two children; error if internal Binary Tree insertion update methods

  30. Binary Trees- Query • What tree is produced by a pre-order traversal of a binary tree ?

  31. Binary Trees - Query 6 8 2 1 4 3

  32. Binary Tree Uses • Heaps / Priority queues • Arithmetic expression trees • Decision trees • Binary-search trees • Database storage (B+ Trees)

  33. Binary Tree Traversals • Preorder and Postorder • Same as general case • When processing children of a node, left child first, right child next • Inorder Traversal • applies to binary trees only • recursively process left subtree, then root, then right subtree

  34. Inorder Traversal for Binary Trees Algorithm inorder(v) Input: Node v Output: Depends on application if isInternal(v) then inorder(leftChild(v)) perform the “visit” action for node v // example: print element(v) if isInternal(v) then inorder(rightChild(v))

  35. Binary Trees - Inorder Traversal - / 8 x 3 3 1

  36. Binary Trees - Expression • Expressions can be represented by a binary tree • The leaves of an expression tree are operands (i.e. constants, variables,etc) • Other nodes are the operators

  37. Expression Trees • Example The expression (a+b*c)+((d*e+f)*g)can be represented as follows :

  38. Expression Trees + + * + g a * f * b c d e

  39. Expression Trees • If you do a post-traversal of the tree, the result is as follows : a b c * + d e f + g * + • Postfix notation of the expression • Compiler design

  40. Expression Trees - Query • Make an expression tree of the following formula : (a*b) * (c+d) - e

  41. Binary Tree Array-Based Implementation • Use array S[1..max] to store elements • derive parent/child relationships from indices • Let i be an array index, S[i] be the node • i = 1 for the root node • left child of S[i] is S[2*i] • right child of S[i] is S[2*i+1] • parent of S[i] is S[i/2] • Slightly different formula if S[0..max-1]

  42. BT Array Implementation continued • Implementations of root(), parent(v), leftChild(v), rightChild() and test methods • simple arithmetic computations • May need an integer n to represent last valid node/first available node in the array • e.g., when implementing a heap • Disadvantages: • maximum size has to be predetermined • space-inefficient for “skewed” trees

  43. Binary Tree Linked Implementation • Need a Node class containing • element • left, right and parent of class Node • usual set/get methods • Binary Tree class now contains • root variable of class Node • size variable (int) to monitor tree size

  44. BT Linked Implementation continued • Access and test methods • all involve inspecting node data • expandExternal(v) • create two nodes and set some pointers • removeAboveExternal(v) • reset child pointer of grandparent to null • dispose garbage nodes (automatic in Java)

  45. Binary Search Trees • For every node x, in the tree, the values of all the keys in the left subtree are smaller than the key value in x and the values of all the keys in the right subtree are larger than the key value in x • Average depth (access time) is O (log(n))

  46. Binary Search Trees 6 6 8 2 2 6 8 1 4 1 4 3 7 3

  47. Binary Search Tree - AVL • Definition- It is a binary search tree with a balance condition- for every node in the tree, the average height of the left and right subtrees can differ by at most one (1).

  48. AVL Binary Search Trees 6 6 8 2 2 6 8 1 4 7 1 4 3 7 3

  49. AVL Binary Search Trees • Binary Search Trees are transformed to AVL Binary Search Trees by a process called rotation

  50. Single Rotation • Consider the binary search tree X (k1<k2, X<k1,Z>k2) k2 k1 Z Z X k1 k2 Z X Y Y Z

More Related