470 likes | 538 Views
8 Tree ADTs. Tree concepts. Applications of Trees. A Tree ADT – requirements, contract. Linked implementation of Trees. Binary Tree ADTs. Binary Search Tree (BST). Non Linear Linked Structures. General term is a graph.
E N D
8Tree ADTs • Tree concepts. • Applications of Trees. • A Tree ADT – requirements, contract. • Linked implementation of Trees. • Binary Tree ADTs. • Binary Search Tree (BST)
Non Linear Linked Structures • General term is a graph. • Applications: many real world networking problems including communications, roads, airline routes. 1 2 3 4 5 6 7
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.
Depth 0 3 Height 3 0 Tree Height and Depth A tree, with height and depth information
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
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).
University Engineering Medicine Science Education SocialScience Humanities Chemistry Physics Biology Mathe-matics ComputerScience Languages History Applications of trees Trees occur frequently in real life: • An organizationtree records the structure of a hierarchical organization, such as the divisional structure within a business or university.
animals worms insects arachnids vertebrates stars sponges ants beetles flies fish amphibians reptiles birds mammals snakes lizards crocodiles Applications of trees (continued) • A taxonomy is a classification of organisms or plants.
Archy George Frank Colin Joe Fred David Maggie Ann Jeff Emma Jon Susie Applications of trees (continued) • A familytree 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.
Example: file hierarchies • A filehierarchy 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.
doc bin lib etc tmp users motd passwd cp grep sort mail aliases Example: file hierarchies (continued) • For example:
Tree ADT: requirements • Requirements: 1 It must be possible to access the root of a tree. 2 It must be possible to access all ancestors of any node in a tree. 3 It must be possible to access all descendants of any node in a tree. 4 It must be possible to add a new node to a tree, either as the root node or as the child of an existing node. 5 It must be possible to remove a given node from a tree, together will all its descendants. 6 It must be possible to traverse a tree.
Tree ADT: contract • Possible contract: class Tree { // Each Tree object is a tree whose elements // are arbitrary objects.
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.
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.
Tree ADT: contract (continued) //////////// Transformers - continued ////////// void setElement (Object elem); // Change the element contained in this node to // be elem
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.
link to parent Archy link to next sibling George Frank Colin Joe link to first child Fred David Maggie Ann Susie Jeff Jon Emma Implementation of unordered trees • Example:
Implementation of unordered trees (cont’d) • Summary of algorithms (where c is the maximum number of children per parent): • O(c) could mean O(n) if tree consists of a root node withn– 1 children. • Typically, though, c does not grow in proportion to n.
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): • O(c) could mean O(n) if tree consists of a root node withn– 1 children.
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.
Building a General Tree • In a general tree each node may have any number of children. • Also any node except root my have siblings.
data A right sibling left child D C B J I H G F E M L K Left Child - Right Sibling Tree Node structure A Tree Node structure could include also a pointer to Node’s parent
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)
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)
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
Preorder • preordertraversal AlgorithmpreOrder(v) “visit” nodev for eachchildw of vdo recursively performpreOrder(w)
Postorder • postorder traversal AlgorithmpostOrder(v) for eachchildwof vdo recursively performpostOrder(w) “visit” nodev • du (disk usage) command in Unix
Preorder Implementation public void preorder(ptnode t) { ptnode ptr; display(t->key); for(ptr = t->lchild; NULL != ptr; ptr = ptr->sibling) { preorder(ptr); } }
Postorder Implementation public void postorder(ptnode t) { ptnode ptr; for(ptr = t->lchild; NULL != ptr; ptr = ptr->sibling) { postorder(ptr); } display(t->key); }
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
Example A B C E D G F K H L M I J
Binary Tree ADT objects: a finite set of nodes either empty or consisting of a root node, left BinaryTree, and right BinaryTree.
A A A B B B C C F G D E D E H I Samples of Binary Trees Complete Binary Tree 1 Skewed Binary Tree 2 3 5 4
A A B C B C F G G E D F D E N O M L J I K H H I Complete binary tree Full binary tree of depth 4 Full BT vs. Complete BT
SLL Representation of BT struct TreeNode{ char data; // Node Information TreeNode *left, *right; // Node Communication }; data left data right left right
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 };
Binary Tree ADT • The C++ Tree SLL ADT implementation: • //////////// Accessors //////////// • int Size () { • return NoNodes; };
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 << ptr->data << " "; • } • }
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 << ptr->data << " "; • } • }
Binary Tree ADT • The C++ Tree SLL ADT implementation: • //////////// Accessors //////////// • // Traverse Tree and print Tree nodes PreOrder • void PreOrder(TreeNode* ptr) { • if(ptr){ • cout << ptr->data << " "; • PreOrder(ptr->left); • PreOrder(ptr->right); • } • }
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 << ptr->data << " "; • InOrder(ptr->right); • } • }
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; • }
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; }
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
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