tree data structure

Click here to load reader

Upload: dana-dia

Post on 15-Aug-2015

71 views

Category:

Education


3 download

TRANSCRIPT

  1. 1. Trees Tree traversal By : Dana Diaa Data structure and algorithms
  2. 2. Tree (ADT) What is a tree ? A set of nodes. Each node can have one or more children . Each node can have at most one parent. Root ( no parent) Leaves ( no child) Node level 1 2 3 4
  3. 3. Binary tree In binary tree , each node has at most two children . In other word , it can have zero children ( empty ) , one or two children but not more than two children . Examples of a binary trees :
  4. 4. binary search tree ( BSTree) Every node entry has a unique key ( keys are not the same in the tree ) . All the keys in the left of a node are less than the key of a node All the keys in the right of a node are greater than the key of a node . Example of a BStree : Left Less than 8 Right Greater than 8
  5. 5. A binary tree but NOT binary search tree
  6. 6. Search a node A binary search tree provide an excellent structure for searching a node . For example : find the node with value 6 . We compare: 6 is 8( the root) ? 6 is less than 8 so we go to the left of node . Then we compare : 6 is 3 ? 6 is greater than 3 so we go right to The right of node . 6 is found .
  7. 7. Tree traversal The process of visiting all nodes in a tree only one time . Two classes : 1 . Breadth first traversal . 2 . Depth first traversal .
  8. 8. Breadth first traversal We can go with two methods : 1. Visiting each node starting from the lowest level ( root ) and moving down level by level , visiting each node from left to right . ( top down from left to right ) . Output : 8 , 3 , 10 ,1 ,6 ,14 ,4 ,7 ,13 Starts
  9. 9. Breadth first traversal (cont.) The other method is : 1. Visiting each node starting from the highest level ( leaves ) and moving up level by level , visiting each node from right to left . ( bottom up from right to left ) . Starts Output : 13 , 7 ,4 , 14 ,6 ,1 ,10 ,3 ,8
  10. 10. Depth first traversal We have to consider three tasks in this type . V visiting a node . L traversing the left sub-tree if any . R traversing the right sub-tree if any . There are six types of depth first traversal , but we will consider three of them : VLR ( Preorder ) LVR ( Inorder ) LRV ( Postorder)
  11. 11. VLR ( Preorder ) VLR VLR VLR VLRVLR VLR VLR VLR VLR Output : 8 ,3 ,1 ,6 ,4 ,7 ,10 ,14 ,13 Assuming that the visit(v) is to output the value
  12. 12. LVR ( Ineorder ) LVR Output : 1 , 3 , 4 , 6 , 7 , 8 ,10 ,13 ,14 Assuming that the visit() is to output the valueLVR LVR LVR LVR LVR LVR LVRLVR
  13. 13. LRV ( Posteorder ) LRV Output : 1 , 4 , 7 ,6 ,3 , 13 , 14 , 10 , 8 Assuming that the visit() is to output the value LRV LRV LRV LRV LRV LRVLRVLRV