Presentation is loading. Please wait.

Presentation is loading. Please wait.

8 - 1 8 Tree ADTs Tree concepts. Applications of Trees. A Tree ADT – requirements, contract. Linked implementation of Trees. Binary Tree ADTs. Binary Search.

Similar presentations


Presentation on theme: "8 - 1 8 Tree ADTs Tree concepts. Applications of Trees. A Tree ADT – requirements, contract. Linked implementation of Trees. Binary Tree ADTs. Binary Search."— Presentation transcript:

1 8 - 1 8 Tree ADTs Tree concepts. Applications of Trees. A Tree ADT – requirements, contract. Linked implementation of Trees. Binary Tree ADTs. Binary Search Tree (BST)

2 8 - 2 Non Linear Linked Structures General term is a graph. Applications: many real world networking problems including communications, roads, airline routes. 6 3 1 4 7 5 2

3 8 - 3 Trees A tree consists of a set of nodes and a set of directed edges A tree can be defined that connect pairs of nodes. We consider only rooted trees. A rooted tree has the following properties. –One node is distinguished as the root. –Every node c, except the root, is connected by an edge from exactly one other node p. –Node p is c's parent, and c is one of p's children. –A unique path traverses from the root to each node. –The number of connects that must be followed is the path length.

4 8 - 4 Tree Height and Depth A tree, with height and depth information Height 3 0 Depth 0 3

5 8 - 5 Trees Nodes with the same parent are called siblings An alternative definition of the tree is recursive: Either a tree is empty or it consists of a root and zero or more nonempty subtrees T,, T2,..., Tk, each of whose roots are connected by an edge from the root A tree viewed recursively

6 8 - 6 Tree concepts A tree is a hierarchical collection of elements, and is a generalization of the binary trees. A tree consists of nodes. Each node has an element, and has branches leading to a number of other nodes (its children). The tree has a unique root node. Every node, apart from the root node, is the child of exactly one other node (its parent).

7 8 - 7 Applications of trees Trees occur frequently in real life: An organization tree records the structure of a hierarchical organization, such as the divisional structure within a business or university. University EngineeringMedicineScienceEducationSocial Science Humanities ChemistryPhysicsBiologyMathe- matics Computer Science LanguagesHistory

8 8 - 8 Applications of trees (continued) A taxonomy is a classification of organisms or plants. animals wormsinsectsarachnidsvertebratesstarssponges antsbeetlesfliesfishamphibiansreptilesbirdsmammals snakeslizardscrocodiles

9 8 - 9 Applications of trees (continued) A family tree records human parent–child relationships. –Our strict definition limits us to one parent per child, but we could model a complete family history by a pair of trees, one for mother–child relationships, and another for father–child relationships. Archy GeorgeFrankColinJoe FredDavidMaggieAnn JeffEmmaJon Susie

10 8 - 10 Example: file hierarchies A file hierarchy is a collection of documents (or plain files) and folders (or directories). A folder can contain documents and other folders, to any depth. We can model a file hierarchy by a tree in which documents are modeled by leaf nodes and (nonempty) folders are modeled by parent nodes.

11 8 - 11 Example: file hierarchies (continued) For example: docbinlibetc cpgrepsortmail motdpasswd aliases tmpusers

12 8 - 12 Tree ADT: requirements Requirements: 1It must be possible to access the root of a tree. 2It must be possible to access all ancestors of any node in a tree. 3It must be possible to access all descendants of any node in a tree. 4It must be possible to add a new node to a tree, either as the root node or as the child of an existing node. 5It must be possible to remove a given node from a tree, together will all its descendants. 6It must be possible to traverse a tree.

13 8 - 13 Tree ADT: contract Possible contract: class Tree { // Each Tree object is a tree whose elements // are arbitrary objects.

14 8 - 14 Tree ADT: contract (continued) //////////// Accessors //////////// public: TreeNode root (); // Return the root node of this tree. TreeNode parent (TreeNode node); // Return the parent of node in this tree, or null // if node is the root node. int childCount (TreeNode node); // Return the number of children of node in // this tree. Object getElement (); // Return the element contained in this node.

15 8 - 15 Tree ADT: contract (continued) //////////// Transformers //////////// void makeRoot (Object elem); // Make this tree consist of just a root node // containing element elem. TreeNode addChild ( TreeNode node, Object elem); // Add a new node containing elem as a child of // node in this tree, and return the new node. The // new node has no children of its own. void remove (TreeNode node); // Remove node from this tree, together with all its // descendants.

16 8 - 16 Tree ADT: contract (continued) //////////// Transformers - continued ////////// void setElement (Object elem); // Change the element contained in this node to // be elem

17 8 - 17 Linked implementation of trees There are many possible implementations of the tree ADT. Here will we consider a linked implementation based on SLLs. We can distinguish between two different kinds of tree: In an unordered tree, each parent has a set of children. In an ordered tree, each parent has a list of children. A Set can be built as an unsorted SLL. This will be adequate here, since the number of children per parent tends to be quite small.

18 8 - 18 Implementation of unordered trees Example: Archy FrankGeorge Fred ColinJoe David SusieJeff Maggie Ann Emma Jon link to first child link to next sibling link to parent

19 8 - 19 Implementation of unordered trees (cont’d) Summary of algorithms (where c is the maximum number of children per parent): OperationAlgorithmTime complexity parent Follow link (trivial)O(1) addChild SLL insertion before first nodeO(1) remove SLL deletionO(c)O(c) O(c) could mean O(n) if tree consists of a root node with n – 1 children. Typically, though, c does not grow in proportion to n.

20 8 - 20 Implementation of ordered trees To implement an ordered tree, we must preserve the order in which the children are added. So add each new child at the end of the SLL. Summary of algorithms (where c is the maximum number of children per parent): OperationAlgorithmTime complexity parent Follow link (trivial)O(1) addChild SLL insertion after last nodeO(c)O(c) remove SLL deletionO(c)O(c) O(c) could mean O(n) if tree consists of a root node with n – 1 children.

21 8 - 21 Specialized tree ADTs Our tree ADT is very general: –it allows nodes to contain arbitrary elements; –it allows each node to have an arbitrary number of children. Often, a particular application will require a more specialized structure. In this case, we can design and implement a specialized tree ADT.

22 8 - 22 Building a General Tree In a general tree each node may have any number of children. Also any node except root my have siblings.

23 8 - 23 Left Child - Right Sibling ABCD E F G H I J K LM data left child right sibling Tree Node structure A Tree Node structure could include also a pointer to Node’s parent

24 8 - 24 Tree ADT Objects: any type of objects can be stored in a tree Methods: accessor methods –root() – return the root of the tree –parent(p) – return the parent of a node –children(p) – returns the children of a node query methods –size() – returns the number of nodes in the tree –isEmpty() - returns true if the tree is empty –elements() – returns all elements –isRoot(p), isInternal(p), isExternal(p)

25 8 - 25 Tree Implementation A C++ implementation for a Tree Node is: struct tnode { int key;// Node Information struct tnode* lchild;// Node Communication struct tnode* sibling; // Node Communication } ; -Create a tree with three nodes (one root & two children) -Insert a new node (in tree with root R, as a new child at level L) -Delete a node (in tree with root R, the first child at level L)

26 8 - 26 Tree Traversal Two main methods: –Preorder –Postorder Recursive definition PREorder: –visit the root –traverse in preorder the children (subtrees) POSTorder –traverse in postorder the children (subtrees) –visit the root

27 8 - 27 Preorder preorder traversal Algorithm preOrder(v) “visit” node v for each child w of v do recursively perform preOrder(w)

28 8 - 28 Postorder postorder traversal Algorithm postOrder(v) for each child w of v do recursively perform postOrder(w) “visit” node v du (disk usage) command in Unix

29 8 - 29 Preorder Implementation public void preorder(ptnode t) { ptnode ptr; display(t->key); for(ptr = t->lchild; NULL != ptr; ptr = ptr->sibling) { preorder(ptr); }

30 8 - 30 Postorder Implementation public void postorder(ptnode t) { ptnode ptr; for(ptr = t->lchild; NULL != ptr; ptr = ptr->sibling) { postorder(ptr); } display(t->key); }

31 8 - 31 Binary Trees A special class of trees: max degree for each node is 2 (children) Recursive definition: A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree. Any tree can be transformed into binary tree. –by left child-right sibling representation

32 8 - 32 Example J IM H L A B C D E F G K

33 8 - 33 Binary Tree ADT objects: a finite set of nodes either empty or consisting of a root node, left BinaryTree, and right BinaryTree.

34 8 - 34 Samples of Binary Trees ABABABCGEIDHF Complete Binary Tree Skewed Binary Tree ECD 1 2 3 4 5

35 8 - 35 Full BT vs. Complete BT A B C G E K D J F I H O N M L Full binary tree of depth 4 A B C G E I D H F Complete binary tree

36 8 - 36 SLL Representation of BT struct TreeNode{ char data; // Node Information TreeNode *left, *right; // Node Communication }; dataleftright data leftright

37 8 - 37 Binary Tree ADT The C++ Tree SLL ADT implementation: class TreeSLL{ private: int NoNodes; public: //////////// Constructor //////////// TreeNode *Root; TreeSLL (char c) { NoNodes = 0; Root = NEW (c); // Initiates the Root };

38 8 - 38 Binary Tree ADT The C++ Tree SLL ADT implementation: //////////// Accessors //////////// int Size () { return NoNodes;};

39 8 - 39 Binary Tree ADT The C++ Tree SLL ADT implementation: //////////// Accessors //////////// // Traverse Tree and print Tree nodes PostOrder void PostOrder(TreeNode* ptr) { if(ptr){ PostOrder(ptr->left); PostOrder(ptr->right); cout data << " "; }

40 8 - 40 Binary Tree ADT The C++ Tree SLL ADT implementation: //////////// Accessors //////////// // Traverse Tree and print Tree nodes PostOrder void PostOrder(TreeNode* ptr) { if(ptr){ PostOrder(ptr->left); PostOrder(ptr->right); cout data << " "; }

41 8 - 41 Binary Tree ADT The C++ Tree SLL ADT implementation: //////////// Accessors //////////// // Traverse Tree and print Tree nodes PreOrder void PreOrder(TreeNode* ptr) { if(ptr){ cout data << " "; PreOrder(ptr->left); PreOrder(ptr->right); }

42 8 - 42 Binary Tree ADT The C++ Tree SLL ADT implementation: //////////// Accessors //////////// // Traverse Tree and print Tree nodes InOrder void InOrder(TreeNode* ptr) { if(ptr){ InOrder(ptr->left); cout data << " "; InOrder(ptr->right); }

43 8 - 43 Binary Tree ADT The C++ Tree SLL ADT implementation: //////////// Transformers //////////// // Create the Binary Tree Node: TreeNode* NEW(char c) { TreeNode* p = new TreeNode; p->data=c; p->left=p->right=NULL; NoNodes++; return p; }

44 8 - 44 Binary Tree ADT The C++ Tree SLL ADT implementation: //////////// Transformers //////////// // Add node as a left child of p void AddLeft(TreeNode* p,char c) { TreeNode* q=NEW(c); p->left=q; } // Add node as a left child of p void AddRight(TreeNode* p,char c) { TreeNode* q=NEW(c); p->right=q; }

45 8 - 45 Binary Tree ADT void main() { TreeSLL BTree('-'); // 5*x / 2 - 6 BTree.AddLeft(BTree.Root,'/'); BTree.AddRight(BTree.Root->left,'2'); BTree.AddLeft(BTree.Root->left,'+'); BTree.AddLeft(BTree.Root->left->left,'x'); BTree.AddRight(BTree.Root->left->left,'3'); BTree.AddRight(BTree.Root,'6'); cout << "No of Tree Nodes = " << BTree.Size () << endl; cout << "Postorder\t"; // Postorder x 3 + 2 / 6 - BTree.PostOrder(BTree.Root); cout << endl; cout << "Preorder \t"; // Preorder - / + x 3 2 6 BTree.PreOrder(BTree.Root); cout << endl; cout << "Inorder \t"; // Inorder x + 3 / 2 - 6 BTree.InOrder(BTree.Root); cout << endl; } BT_Trav2.CPP

46 8 - 46 Binary Tree ADT Output No of Tree Nodes = 7 Postorder x 3 + 2 / 6 - Preorder - / + x 3 2 6 Inorder x + 3 / 2 - 6 BT_Trav2.CPP


Download ppt "8 - 1 8 Tree ADTs Tree concepts. Applications of Trees. A Tree ADT – requirements, contract. Linked implementation of Trees. Binary Tree ADTs. Binary Search."

Similar presentations


Ads by Google