240 likes | 367 Views
Definition. The ADT Binary Tree is a finite set of nodes which is either empty or consists of a data element (called the root ) and two disjoint binary trees (called the left and right subtrees of the root), together with a number of access procedures. r.
E N D
Definition The ADT Binary Treeis a finite set of nodes which is either empty or consists of a data element (called the root) and two disjoint binary trees (called the leftand rightsubtrees of the root), together with a number of access procedures. r r = a nodeTL = left binary treeTR = right binary tree data elem TL TR The ADT Binary Tree Nodes with no successors are called leaves. The roots of the left and right subtrees of a node “i” are called the “children of i”; the node i is their parent;they are siblings. A child has one parent. A parent has at most two children. Uni4: ADT Trees
Applications of Binary Trees • Expression trees (e.g., in compiler design) for checking that the expressions are well formed and for evaluating them. • ‒ leaf nodes are operands (e.g. constants) • ‒ non leaf nodes are operators + a * - d b c • Huffman coding trees,for implementing data compression algorithms: • ‒ each leaf is a symbol in a given alphabet • ‒ code of the symbol constructed following the path from root to the leaf (left link is 0 and • right link is 1) a d b c a = 0, b = 100, c = 101, d = 11 Uni4: ADT Trees
Some definitions 1.Nodes are arranged inlevels. The level of a nodeis 1 if the node is the root of the tree; otherwise it is defined to be 1 more than the level of its parent. 2.Theheight of a tree T is the number of levels in the tree. It can be defined, recursively, asheight(T.createTree( ) ) = 0; height(T.createBTree(Item, LTree, RTree)) = 1+ max(height(LTree), height(RTree)); 3.Theshortest path in a tree T is defined asShortestPath(T.createTree( )) = 0 ShortestPath(T.createBTree(Item, LTree, RTree)) = 1+ min((ShortestPath(LTree), ShortestPath(RTree)); 4.A perfectly balanced tree (or full) is a tree whose height and its shortest path have the same value. Uni4: ADT Trees
Level 1 Level 2 Perfectlybalanced Level 3 Level 1 Level 2 ill-balanced Level 3 Level 4 Example trees A C B F G D E J K L M N P Uni4: ADT Trees
S Level 1 T Level 2 U Level 3 V Level 4 W Level 5 X Level 6 Example trees very ill-balanced Uni4: ADT Trees
Theorem The number of nodes in a perfectly balanced tree of height h (0) is 2h - 1 nodes. Proof The proof is by induction on h:Base Case: h=0. Empty tree is balanced; 20 – 1 = 0; Inductive Hypothesis: suppose the theorem holds for k, with 0 k.In this case a perfectly balanced tree has 2k – 1 nodes. We want to show it holds for a perfectly balanced tree with height k+1. A perfectly balanced tree of height k+1 consists of a root node and 2 subtrees each of height k. Total number of nodes is: (2k – 1) + 1 + (2k – 1) = = 2*2k – 1 = 2k+1 – 1 So a perfectly balancedtree of height h has 2h - 1 nodes Uni4: ADT Trees
Rector Dean of Eng. Dean of Science Head ofPhysics Head ofCiv Eng Additional Definition Definition: A complete tree of height h is a tree which is full down to level h-1, with level h filled in from left to right. Head ofMaths A complete tree The height of a complete or perfectly balanced tree with n nodes is: h = log2(n+1) (rounded up). Uni4: ADT Trees
Methods for “visiting” each node of a tree. Given the recursive definition of a binary tree, we could think of using a recursive traversal algorithm: pseudocode r traverse(binaryTree) if (binaryTree is not empty) { traverse(Left subtree of binaryTree’s root); traverse(Right subtree of binaryTree’s root); } data item TL TR Not complete: it doesn’t include operation for visiting the root r When shall we visit the root node r? • visit r before traversing both r’s subtrees; • visit r after it has traversed r’s left subtree; but before traversing r’s right subtree • visit r after it has traversed both of r’s subtrees. Tree Traversals Uni4: ADT Trees
Tree Traversals Preorder(Tree) if (Tree is not empty){Display the data in the root node;preorder(Left subtree of Tree’s root);preorder(Right subtree of Tree’s root);} Pre-order: Visit the root node before traversing the subtrees Inorder(Tree) if (Tree is not empty) { inorder(Left subtree of Tree’s root);Display the data in the root node;inorder(Right subtree of Tree’s root); } In-order: Visit the root after traversing left sub-tree and before right sub-tree. Postorder(Tree) if (Tree is not empty) {postorder(Left subtree of Tree’s root);postorder(Right subtree of Tree’s root);Display the data in the root node;} Post-order: Visit the root after traversing left sub-tree and right sub-tree. Uni4: ADT Trees
Examples of Tree Traversals 14 Display the nodes of the tree: Pre-order: 14, 17, 9, 53, 30, 50, 11; 17 11 In-order: 9, 17, 30, 53, 50, 14, 11; 9 53 Post-order: 9, 30, 50, 53, 17, 11, 14; 30 50 * Algebraic expression tree: (a+(b-c))*d. + d Pre-order: * + a – b c d . This gives the prefix notation of expressions; a - In-order: a + b – c * d This requires bracketing for representing sub-expressions. It is called infix notation of expressions; b c Post-order: a b c - + d * This gives the postfix notation of expressions. Uni4: ADT Trees
Pre-order, in-order, and post-order tree traversals are depth-first traversals, as (except for the root in pre-order) nodes further away from the root node (i.e. deepest nodes) are visited first. They explore one subtree before exploring another. Recursive algorithms: the run-time implementation of recursion keeps track of the progress through the tree.Iterative algorithms: must keep track of higher-level nodes explicitly, for example, using a stack. Nodes can be pushed during progress away from the root, and can be popped to move back towards the root. Depth-first and Breadth-first traversals Breadth-first traversal visits all the nodes at one level, before moving to another level. Root first, then the child nodes of the root, then the children of the children in the order in which the root’s children were visited. 14 Breadth-first:14, 17, 11, 53, 30, 50 A queueof children of a node must be builtup when the node is visited, so that the correct ordering is maintained at the next level. 11 17 30 50 53 Uni4: ADT Trees
Access Procedures createEmptyTree( ) // post: creates an empty tree createBTree(rootElem) // post: creates a one-node binary tree whose root contains rootElem. createBTree(rootElem leftTree, rightTree) // post: creates a binary tree whose root contains rootElem, and has leftTree and // post: rightTree, respectively, as its left and right subtrees. attachLeft(newElem)// post: Attaches a left child containing newElem to the root of a binary tree attachRight(newElem)// post: Attaches a right child containing newElem to the root of a binary tree attachLeftTree(leftTree)// post: Attaches leftTree as the left subtree of the root of a binary tree. attachRightTree(rightTree)// post: Attaches rightTree as the right subtree of the root of a binary tree. Uni4: ADT Trees
Access Procedures isEmpty( ) // post: determines whether a tree is empty getRootElem( ) // post: retrieves the data element in the root of a non-empty binary tree. getLeftSubtree( )// post: returns the left subtree of a binary tree’s root. getRightSubtree( )// post: returns the right subtree of a binary tree’s root. detachLeftSubtree( )// post: detaches and returns the left subtree of a binary tree’s root. detachRightSubtree( )// post: detaches and returns the right subtree of a binary tree’s root. Uni4: ADT Trees
Axioms for ADT Tree These are only some of the axioms that the access procedures have to satisfy, where Elem is an element, aTree, LTree and RTree are given Binary Trees: • (aTree.createTree( ) ).isEmpty = true • (aTree.createBTree(Elem, LTree, RTree)).isEmpty() = false • (aTree.createTree( )).getRootElem( ) = error • (aTree. createBTree(Elem, LTree, RTree)). getRootElem( ) = Item • (aTree.createTree( )).detachLeftSubtree( ) = error • (aTree.createBTree(Elem, LTree, RTree)). detachLeftSubtree( ) = LTree • (aTree.createTree( )).detachRightSubtree( ) = error • (aTree.createBTree(Elem, LTree, RTree)). detachRightSubtree( ) = RTree Uni4: ADT Trees
0 Pam 0 Pam Sue 1 1 2 Mary 2 Sue Mary Ellen 3 3 5 4 April 4 Ellen April Sara Sara 5 6 7 tree[i] = node numbered i tree[ ] Invariants: • Data from the root always appears in the [0] position of the array; • Suppose that a non-root node appears at position [i]. Then its parent node isalways at location [(i-1)/2] (using integer division). • Suppose that a node appears at position [i] of the array. Then its children (ifthey exist) always appear at locations [2i+1] for the left child and location[2i+2] for the right child. A Static Implementation of Complete Trees Uni4: ADT Trees
root left left right right left right Dynamic implementation of Trees elem elem elem class TreeNode<T>{ private T element;private TreeNode<T> left;private TreeNode<T> right; …} class BinaryTree<T>{ private TreeNode<T> root;……………} Uni4: ADT Trees
The class TreeNode<T> public class TreeNode<T>{ private T element; private TreeNode<T> left, right; public TreeNode(T newElem, TreeNode<T> leftChild, rightChild){element = newElem; left = leftChild; right = rightChild; } public TreeNode(T newElem){element = newElem; left = null; right = null; } public void setElem(T newElem){ element = newElem; } public T getElem(){ return element; } public void setLeft(TreeNode Node){left = Node; } public TreeNode<T> getLeft(){ return left; } public void setRight(TreeNode Node) { right = Node;} public TreeNode getRight(){ return right; } } Uni4: ADT Trees
Dynamic Implementation of BinaryTrees<T> public class LinkedBaseBinaryTree<T> implements BinaryTree<T> { private TreeNode<T> root; private LinkedBasedBinaryTree(T rootElem){ root =new TreeNode(rootElem, null, null);} protected LinkedBasedBinaryTree (TreeNode<T> rootNode){root = rootNode; } protected LinkedBasedBinaryTree (T rootElem, TreeNode<T> left, TreeNode<T> right){ root =new TreeNode(rootElem, left, right);} publicboolean isEmpty( ){ return root == null; } public T getRootElem()throws TreeException{if (root == null){ throw new TreeException(“TreeException: Empty tree”); } else {return root.getElem( ); } } Continue…. The ADT Binary Tree
Dynamic Implementation of BinaryTrees<T> public void attachLeft(T newElem) throws TreeException{ if (!isEmpty( ) && root.getLeft( ) == null){ root.setLeft(new TreeNode<T>(newElem, null, null)); } else { if (isEmpty( )) {throw new TreeException(“TreeException: Empty tree”); } } } public void attachLeftSubtree(BinaryTree<T> leftTree) throws TreeException{ if (isEmpty( )) {throw new TreeException(“TreeException: Empty tree”); } else { if (root.getLeft() != null){throw new TreeException(“Left subtree already exists”);} else { root.setLeft(leftTree.getRoot( ));leftTree.makeEmpty( ); } } public BinaryTree<T> detachLeftSubtree( ) throws TreeException{ if (isEmpty( )){throw new TreeException(“TreeException: Empty tree”); } else {BinaryTree<T>leftTree = new LinkedBasedBinaryTree<T>(root.getLeft( ));root.setLeft(null); return leftTree; } }……… } The ADT Binary Tree
University Engineering Medicine Science Education SocialScience Humanities Chemistry Physics Biology Mathe-matics ComputerScience Languages History General Trees A general tree is a hierarchical collection of elements, and is a generalization of the binary trees. Example applications: Organization tree Uni4: ADT Trees
animals worms insects arachnids vertebrates stars sponges ants beetles flies fish amphibians reptiles birds mammals snakes lizards crocodiles General Trees A general tree is a hierarchical collection of elements, and is a generalization of the binary trees. Example applications: Taxonomy tree Uni4: ADT Trees
doc bin lib etc tmp users motd passwd cp grep sort mail aliases General Trees A general tree is a hierarchical collection of elements, and is a generalization of the binary trees. Example applications: Files hierarchy Uni4: ADT Trees
root Dynamic Implementation of General Trees treeNode elem children treeNode treeNode treeNode elem elem elem children children children class TreeNode<T>{ private T element;private List<TreeNode> children; …} class GeneralTree<T>{ private TreeNode<T> root;……………} Uni4: ADT Trees
Summary • Binary trees provide a hierarchical organisation of data, important in applications. • The implementation of a binary tree is usually reference based. If the tree is complete, an efficient array-based implementation is possible. • Traversing a tree is a useful operation; intuitively, it means to visit every node in the tree. Three different traversal algorithms can be used. • General trees can be implemented making use of a linked list to store the children of a parent node. Uni4: ADT Trees