Chapter 13 The General Binary Tree

Similar documents
Chapter 14 The Binary Search Tree

Binary Trees and Huffman Encoding Binary Search Trees

DATA STRUCTURES USING C

Ordered Lists and Binary Trees

Binary Search Trees (BST)

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Data Structures and Algorithms

Converting a Number from Decimal to Binary

Data Structure [Question Bank]

10CS35: Data Structures Using C

PES Institute of Technology-BSC QUESTION BANK

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Binary Search Trees CMPSC 122

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

7.1 Our Current Model

Chapter 8: Binary Trees

Class Notes CS Creating and Using a Huffman Code. Ref: Weiss, page 433

root node level: internal node edge leaf node Data Structures & Algorithms McQuain

Algorithms and Data Structures

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

International Journal of Advanced Research in Computer Science and Software Engineering

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Data Structures and Algorithms V Otávio Braga

GRAPH THEORY LECTURE 4: TREES

Symbol Tables. Introduction

Data Structure with C

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

TREE BASIC TERMINOLOGIES

Analysis of Algorithms I: Optimal Binary Search Trees

Data Structures. Level 6 C Module Descriptor

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

Algorithms and Data Structures Written Exam Proposed SOLUTION

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

Data Structures and Algorithms(5)

The ADT Binary Search Tree

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

ER E P M A S S I CONSTRUCTING A BINARY TREE EFFICIENTLYFROM ITS TRAVERSALS DEPARTMENT OF COMPUTER SCIENCE UNIVERSITY OF TAMPERE REPORT A

Data Structures, Practice Homework 3, with Solutions (not to be handed in)

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Binary Heap Algorithms

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Analysis of Compression Algorithms for Program Data

Binary Trees (1) Outline and Required Reading: Binary Trees ( 6.3) Data Structures for Representing Trees ( 6.4)

Exam study sheet for CS2711. List of topics

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

A binary search tree is a binary tree with a special property called the BST-property, which is given as follows:

THE SECURITY AND PRIVACY ISSUES OF RFID SYSTEM

Stacks. Linear data structures

COMPUTER SCIENCE. Paper 1 (THEORY)

Parallelization: Binary Tree Traversal

Computing Concepts with Java Essentials

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Graduate Assessment Test (Sample)

AP Computer Science AB Syllabus 1

Data Structures Fibonacci Heaps, Amortized Analysis

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

Cpt S 223. School of EECS, WSU

From Last Time: Remove (Delete) Operation

Java Software Structures

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Sample Questions Csci 1112 A. Bellaachia

Analysis of Algorithms I: Binary Search Trees

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT. Course Curriculum. DATA STRUCTURES (Code: )

Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

Image Compression through DCT and Huffman Coding Technique

encoding compression encryption

Lecture Notes on Binary Search Trees

Data Structures UNIT III. Model Question Answer

Heaps & Priority Queues in the C++ STL 2-3 Trees

Data Structures Using C++

OPTIMAL BINARY SEARCH TREES

Efficient Data Structures for Decision Diagrams

Section IV.1: Recursive Algorithms and Recursion Trees

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

S. Muthusundari. Research Scholar, Dept of CSE, Sathyabama University Chennai, India Dr. R. M.

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Glossary of Object Oriented Terms

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Persistent Binary Search Trees

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

DNS LOOKUP SYSTEM DATA STRUCTURES AND ALGORITHMS PROJECT REPORT

Information, Entropy, and Coding

Module 2 Stacks and Queues: Abstract Data Types

Data Structures. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

Java Interview Questions and Answers

Lecture Notes on Binary Search Trees

Keys and records. Binary Search Trees. Data structures for storing data. Example. Motivation. Binary Search Trees

Iterators. Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.

Chapter 8: Bags and Sets

Full and Complete Binary Trees

Optimal Binary Search Trees Meet Object Oriented Programming

Structural Design Patterns Used in Data Structures Implementation

Let s put together a Manual Processor

Unordered Linked Lists

Transcription:

Chapter 13 The General Binary Tree In Chapter 6 we examined the heap, a partially ordered complete binary tree. We implemented the heap ADT as an array container because the special properties of a complete binary tree make possible an elegant array implementation. In general, though, binary trees are implemented as linked containers. In this chapter we will discuss the binary tree ADT and implement it as a linked container. 13.1 Our Current Model Our current UML class diagram is shown below in Figure 13.1. It includes class TreeContainer and class BinaryTree, which has two nested types, class BinaryTreeNode and interface NodeProcessor. To simplify the diagram, nested classes SLNode and DLNode have been omitted.

132 Chapter 13 The General Binary Tree Fig. 13.1. Our current software design, which includes a classifier for linked trees in general and a classifier for linked binary trees more specifically

13.2 The Binary Tree ADT 133 13.2 The Binary Tree ADT The binary tree ADT appears below. An explanation of the traversal operations follows the ADT specification. binary tree: See Chapter 6. operations: clear() Make the collection empty. height() What is the height of the tree? inordertraverse(processor) Perform an inorder traversal of the tree, applying some operation to each node. isempty() Is the collection empty? postordertraverse(processor) - Perform a postorder traversal of the tree, applying some operation to each node. preordertraverse(processor) - Perform a preorder traversal of the tree, applying some operation to each node. size() How many elements are in the collection? To traverse a binary tree is to visit each of the tree's nodes. It is not always necessary to visit the nodes in any particular order, but various applications of the binary tree ADT require one or more of three standard orders of traversal. We will examine these three standard traversals by way of example, using the tree in Figure 13.2. Fig. 13.2. An example tree for traversal

134 Chapter 13 The General Binary Tree A preorder traversal visits a given node before visiting either of the node's children (and their subtrees). A preorder traversal of the tree from Figure 13.2 visits the nodes in the following order: 1 2 4 5 3 6 7 8. An inorder traversal visits a given node's left child (and the left child's subtree), then the node itself, then the node's right child (and the right child's subtree). An inorder traversal of the example tree visits the nodes in the following order: 4 2 5 1 6 3 8 7. A postorder traversal visits a given node's two subtrees before visiting the node itself. A postorder traversal of the tree in Figure 13.2 visits the nodes in the following order: 4 5 2 6 8 7 3 1. 13.3 Binary Tree Implementation Class TreeContainer, which class BinaryTree will specialize, is shown below. public abstract class TreeContainer extends LinkedContainer protected Node root; // Any linked tree has a root node. public void clear() root = null; super.clear(); Class BinaryTree extends class TreeContainer and also contains static member class BinaryTreeNode, which subclasses Node, and member interface NodeProcessor. Any class that realizes interface NodeProcessor must offer a public method called processnode, which accepts an argument of type BinaryTreeNode. This gives our traversals great versatility; we can process all the nodes of a Binary- Tree in any way we choose simply by coding a class that fulfills the contract set forth by the interface.

13.3 Binary Tree Implementation 135 public abstract class BinaryTree extends TreeContainer public static abstract class BinaryTreeNode extends Node public BinaryTreeNode leftchild, rightchild, parent; public BinaryTreeNode(Object dat) super(dat); public BinaryTreeNode(Object dat, BinaryTreeNode lc, BinaryTreeNode rc, BinaryTreeNode par) super(dat); leftchild = lc; rightchild = rc; parent = par; public boolean isleaf() return leftchild == null && rightchild == null; public interface NodeProcessor void processnode(binarytreenode node); /* All of the operations are ultimately carried out recursively. Our pattern of development is to write a recursive helper method and wrap a call(s) to that method in the public method that corresponds to the target operation of the ADT. precondition: N/A postcondition: The tree's height has been returned. */ protected int heighthelper(binarytreenode current, int ht) if (current == null) return ht; return Math.max(heightHelper(current.leftChild, ht + 1), heighthelper(current.rightchild, ht + 1)); /* Method height() corresponds to the binary tree operation of same name. height() simply calls heighthelper(), to which it passes the root node and the height of an empty tree. */ public int height() return heighthelper((binarytreenode)root, -1);

136 Chapter 13 The General Binary Tree protected void inorder(binarytreenode node, NodeProcessor processor) if (node!= null) inorder(node.leftchild, processor); processor.processnode(node); if (node!= null) inorder(node.rightchild, processor); public void inordertraverse(nodeprocessor processor) inorder((binarytreenode)root, processor); protected void postorder(binarytreenode node, NodeProcessor processor) if (node!= null) postorder(node.leftchild, processor); postorder(node.rightchild, processor); processor.processnode(node); public void postordertraverse(nodeprocessor processor) postorder((binarytreenode)root, processor); protected void preorder(binarytreenode node, NodeProcessor processor) processor.processnode(node); if (node!= null) preorder(node.leftchild, processor); preorder(node.rightchild, processor); public void preordertraverse(nodeprocessor processor) preorder((binarytreenode)root, processor);

13.4 Binary Tree Applications 137 13.4 Binary Tree Applications Several important kinds of binary tree are the Huffman coding tree (which is used in data compression), the expression tree, the decision tree (which is used in expert systems), and the binary search tree (BST) (which is the subject of the next chapter). Here we will discuss Huffman coding trees and expression trees. 13.4.1 Huffman Coding The familiar ASCII and UNICODE character-encoding schemes use fixedlength codes to represent characters; each character of the ASCII set is represented by an eight-bit pattern, and each UNICODE character is represented by a 16-bit pattern. The idea behind Huffman coding is to reduce the space requirement for data by exploiting the fact that some characters are likely to appear more frequently than others. In English-language text, for example, the letter 'e' typically occurs far more often than does 'x' or 'z'. Huffman coding responds to these different frequencies of occurrence by assigning variable-length codes to the various characters; more frequently occurring characters are assigned shorter codes, and letters that occur less frequently are assigned longer codes. Let us see how Huffman codes are assigned by using the example letterfrequency table shown below. The particular frequencies have been arbitrarily chosen and do not matter; what matters is the frequency of any given letter relative to the frequency of any other letter. Table 13.1. A sample table of letter frequencies to be used in assigning Huffman codes Letter Frequency A 100 C 53 E 133 M 60 U 44 Z 8 The first step in building a Huffman coding tree is to sort the letters in ascending order by frequency. Each letter will be a leaf in the final tree.

138 Chapter 13 The General Binary Tree Next, the first two letters, those with the lowest frequencies, are removed from the list and become the children of a new internal node. The internal node has no letter, but its frequency is the sum of the frequencies of its children. This new internal node is then placed on the list so as to maintain the list's sorted ordering. This process continues until the list has only one element, the root of the final Huffman coding tree. The remaining steps of building our example tree are shown in the following diagrams.

13.4 Binary Tree Applications 139

140 Chapter 13 The General Binary Tree Fig. 13.3. The Huffman coding tree corresponding to the letter frequencies from Table 13.1 Notice that in the final diagram each edge to a left child has been labeled with a 0, and each edge to a right child has been labeled with a 1. This labeling of edges is used to determine the Huffman codes; the code for a given letter is the sequence of 0s and 1s encountered on the path from the root to that letter. The table below shows the Huffman codes obtained from the tree of Figure 13.3. This encoding clearly represents a significant savings compared to an ASCII or UNICODE encoding. Table 13.2. The Huffman codes obtained from the Huffman coding tree of Figure 13.3 Letter Frequency Code Length A 100 01 2 C 53 101 3 E 133 11 2 M 60 00 2 U 44 1001 4 Z 8 1000 4 Huffman coding is often useful for compressing binary data as well as text. The popular MP3 format, for example, uses Huffman coding.

13.4 Binary Tree Applications 141 13.4.2 Expression Trees The binary tree offers an alternative to the stack-based transformation and evaluation of arithmetic expressions described in Chapter 7. Expression trees for the expressions ((3 + 6) % 7) ^ 5-1 and 3 + 6 % 7 ^ 5-1 are shown below in Figure 13.4. Fig. 13.4. Two example expression trees; an expression tree's leaves are operands, its internal nodes operators An expression tree need not store parentheses because the correct order of operations inheres in the tree's structure. Preorder, inorder, and postorder traversals of an expression tree yield prefix, infix, and postfix expressions, respectively.

142 Chapter 13 The General Binary Tree Huffman coding trees and expression trees are examples of full binary trees. Any node of a full binary tree has either zero or two children. Some books reverse the definitions of full and complete binary trees presented here. Exercises 1. Add attributes and operations to the class diagram shown at the beginning of the chapter. 2. We implemented NodeProcessor as a member interface. Suggest an equivalent alternative. 3. Design and code a class called NodePrinter that realizes interface NodeProcessor. Class NodePrinter's processnode method should output the data field of its target node to a chosen java.io.printstream. In the next chapter we will implement a concrete subclass of BinaryTree that will allow you to test your NodePrinter class. 4. Design a node class for a tree whose nodes have an indefinite number of children. 5. Design an algorithm for building an expression tree from an infix expression. 6. How might an expression tree be evaluated?