BINARY TREE CSC248 – Data Structure.

Slides:



Advertisements
Similar presentations
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Advertisements

TREES Chapter 6. Trees - Introduction  All previous data organizations we've studied are linear—each element can have only one predecessor and successor.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
CS 171: Introduction to Computer Science II
Trees Chapter 8.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A12 – Binary Trees.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
1.1 Data Structure and Algorithm Lecture 12 Binary Search Trees Topics Reference: Introduction to Algorithm by Cormen Chapter 13: Binary Search Trees.
Kymberly Fergusson CSE1303 Part A Data Structures and Algorithms Summer Semester 2003 Lecture A12 – Binary Trees.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Trees. Node structure Data A data field and two pointers, left and right.
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Review Binary Tree Binary Tree Representation Array Representation Link List Representation Operations on Binary Trees Traversing Binary Trees Pre-Order.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templatized Tree.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
12-CRS-0106 REVISED 8 FEB 2013 CSG2A3 ALGORITMA dan STRUKTUR DATA.
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
Trees Chapter 8. Chapter 8: Trees2 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information To learn how.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
CISC220 Fall 2009 James Atlas Lecture 13: Trees. Skip Lists.
CMSC 341 Introduction to Trees. 8/3/2007 UMBC CMSC 341 TreeIntro 2 Tree ADT Tree definition  A tree is a set of nodes which may be empty  If not empty,
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
1 Storing Hierarchical Information Lists, Stacks, and Queues represent linear sequences Data often contain hierarchical relationships that cannot be expressed.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
Tree Traversals, TreeSort 20 February Expression Tree Leaves are operands Interior nodes are operators A binary tree to represent (A - B) + C.
CSC 172 DATA STRUCTURES. LISTS We have seen lists: public class Node { Object data; Node next; } 
Binary Trees In computer science, a binary tree is a tree data structure in which each node has at most two children, which are referred to as the left.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
Binary Search Trees (BST)
Rooted Tree a b d ef i j g h c k root parent node (self) child descendent leaf (no children) e, i, k, g, h are leaves internal node (not a leaf) sibling.
TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.
Trees Chapter 10. CS 308 2Chapter Trees Preview: Preview: The data organizations presented in previous chapters are linear, in that items are one.
1 CMSC 341 Introduction to Trees Textbook sections:
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
DS.T.1 Trees Chapter 4 Overview Tree Concepts Traversals Binary Trees Binary Search Trees AVL Trees Splay Trees B-Trees.
TREES From root to leaf. Trees  A tree is a non-linear collection  The elements are in a hierarchical arrangement  The elements are not accessible.
Trees Chapter 15.
Recursive Objects (Part 4)
Week 6 - Wednesday CS221.
Binary Search Tree (BST)
Trees.
CMSC 341 Introduction to Trees.
Section 8.1 Trees.
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
TREE DATA STRUCTURE Data Structure 21-Sep-18 Tree
Binary Trees, Binary Search Trees
Chapter 7 TREES.
Find in a linked list? first last 7  4  3  8 NULL
Binary Search Trees.
Binary Trees, Binary Search Trees
Trees Chapter 10.
Trees.
Trees Trees.
Binary Search Trees CS 580U Fall 17.
Binary Trees, Binary Search Trees
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
NATURE VIEW OF A TREE leaves branches root. NATURE VIEW OF A TREE leaves branches root.
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

BINARY TREE CSC248 – Data Structure

What is a TREE? Is a hierarchical structure that places elements in nodes along branches that originate from a root. Nodes in a tree are subdivided into levels in which the topmost level holds the root node. Any node in a tree can have multiple successors at the next level. A tree is a nonlinear structure. A tree can be viewed as a recursive data structure. Because trees are made up of subtrees.

What is a TREE? Examples of a tree structure

Tree Terminology

What is a BINARY TREE? It is a simplest form of a tree. is a tree data structure in which each node has at most two child nodes usually known as "left" and "right“ Any node in the data structure can be reached by starting at root node and repeatedly following references to either the left or right child.

What is a BINARY TREE? Examples of a binary tree data structure

Graphical Representation of Binary Tree

Properties of Binary Tree Branch Line from the root element to a subtree Leaf A leaf has no branches going down from it Height Number of branches between the root and the farthest leaf Level Number of branches between the root and element x Also known as element’s depth Path As sequence of element Level 1 2 3 branch Height of the tree = 3 Path between 2 to 5 = 2 7 6 5 leaf Example

Types of Binary Tree Strictly Binary Tree (SBT) Full Binary Tree (FBT) Each node that’s not a leaf has both left and right subtree Full Binary Tree (FBT) A tree with leaves only at the last level

BINARY SEARCH TREE (BST) sometimes also known as ordered or sorted binary tree, is a a node-based binary tree data structure which has the following properties:- The left subtree of a node contains only nodes with keys less than the node's key (All nodes in LEFT subtree are < ROOT node) The right subtree of a node contains only nodes with keys greater than or equal to the node's key (All nodes in RIGHT subtree are >= ROOT node) Both the left and right subtrees must also be binary search trees.

BINARY SEARCH TREE (BST) All nodes in LEFT subtree are < ROOT node All nodes in RIGHT subtree are >= ROOT node Both the left and right subtrees must also be binary search trees.

BINARY SEARCH TREE (BST) INORDER traversal on BST will give data in ascending order. PREORDER or POSTORDER traversal will give data in different order. The major advantage of binary search trees over other data structures is that the related sorting and search algorithms such as in-order traversal can be very efficient.

EXERCISE Identify the type of the following tree diagram:

EXERCISE Determine whether the following tree is a binary tree

TREE TRAVERSAL A tree data structure can store many information in a particular order to access and store. Accessing data in tree data structure is called tree traversal. Tree traversal is done recursively. Whenever a subtree is met, the traversal order starts again There are three common ways to traverse the tree :- In-order traversal (left, root, right) Pre-order traversal (root, left, right) Post-order traversal (left, right, root)

IN-ORDER TRAVERSAL For each tree or subtree – traversal starts from LEFT node, the ROOT and then the RIGHT node The algorithm, assuming that is a binary tree :

PRE-ORDER TRAVERSAL For each tree or subtree – traversal starts from ROOT node, the LEFT and then the RIGHT node The algorithm, assuming that is a binary tree

POST-ORDER TRAVERSAL For each tree or subtree – traversal starts from LEFT node, the RIGHT and then the ROOT node The algorithm, assuming that it is a binary tree

EXPRESSION TREE A binary expression tree represents an arithmetic expression (infix, prefix and postfix). In an expression tree, each operator is an interior node whose children as operands or subexpressions. Operands are in leaf nodes can be built with prefix and postfix expression only. Any infix expression must be converted to prefix or postfix expression in order to build the expression tree prefix or postfix expression will produce the same expression tree if it comes from the same infix expression

Building the Expression Tree Using Prefix Expression Evaluate prefix expression from LEFT to RIGHT. Any operator must be at the ROOT, and any operand must be at the leaf Always open the LEFT branch first until no more branch can be opened. Then open the RIGHT branch.

Building the Expression Tree

Using Postfix Expression Evaluate postfix expression from RIGHT to LEFT. Any operator must be at the ROOT, and any operand must be at the leaf Always open the RIGHT branch first until no more branch can be opened. Then open the LEFT branch.

Using Postfix Expression

TRAVERSING THE EXPRESSION TREE Applying a different traversing technique to an expression tree will result a different mathematical expression. There are three traversing technique : INORDER Traversal gives infix expression (LEFT, ROOT, RIGHT)  (OPERAND,OPERATOR,OPERAND) PREORDER Traversal gives prefix expression (ROOT, LEFT, RIGHT)  (OPERATOR,OPERAND,OPERAND) POSTORDER Traversal gives postfix expression (LEFT, RIGHT, ROOT)  (OPERAND,OPERAND,OPERATOR

Traverse the tree in inorder, preorder and postorder

INORDER TRAVERSAL The traversal result is: 3 + 7 * 2 -1

PREORDER TRAVERSAL The traversal result: - + 3 * 7 2 1

Post-order traversal The traversal result: 3 7 2 * + 1 -

Binary Search Tree Implementation BST uses dynamic storage space BST ADT has to be modified to suit the type of data to be stored. ADT can’t be common because data has to be compared to locate proper position. BST uses recursion method/technique. Each node in a tree has 3 elements : Left node reference/link Data Right node reference/link

Tree Node Structure (for primitive data type integer) Class : TreeNode Attributes: leftNode // left node reference/link rightNode // right node reference/link data // represent data Methods : Constructor() // normal constructor insert() // insert a TreeNode into a tree

//normal constructor to initialize data to d public TreeNode(int d) public class TreeNode { TreeNode left; TreeNode right; int data; //normal constructor to initialize data to d //and make this a leaf node public TreeNode(int d) left=right=null; data = d; } // Insert a TreeNode into a Tree that contains // contains nodes. Ignore duplicate values. public void insert( int d ) { if ( d < data ) if ( left == null ) left = new TreeNode( d ); else left.insert( d ); } if ( d > data ) if ( right == null ) right = new TreeNode( d ); right.insert( d );

Binary Search Tree Structure Class : BSTree Attributes: root // roott node reference Methods : public BSTree() // default constructor public void insertNode(element) public void preorderTraversal() private void preorderHelper(node) public void inorderTraversal() private void inorderHelper(node) public void postorderTraversal() private void postorderHelper(node)

// Insert a new node in the binary search tree. public class BSTree { TreeNode root; // Construct an empty Tree public BSTree() { root = null; } // Insert a new node in the binary search tree. // If the root node is null, create the root node here. // Otherwise, call the insert method of class TreeNode. public void insertNode( int d ) if ( root == null ) root = new TreeNode( d ); else root.insert( d ); }

public void PreOrder() { RecurPreOrder( root ); } // Preorder Traversal public void PreOrder() { RecurPreOrder( root ); } // Recursive method to perform preorder traversal private void RecurPreOrder( TreeNode node ) if ( node == null ) return; System.out.print( node.data + " " ); RecurPreOrder( node.left ); RecurPreOrder( node.right );

private void RecurInOrder( TreeNode node ) if ( node == null ) return; // Inorder Traversal public void InOrder() { RecurInOrder( root ); } // Recursive method to perform inorder traversal private void RecurInOrder( TreeNode node ) if ( node == null ) return; RecurInOrder( node.left ); System.out.print( node.data + " " ); RecurInOrder( node.right );

public void PostOrder() { RecurPostOrder( root ); } // Postorder Traversal public void PostOrder() { RecurPostOrder( root ); } // Recursive method to perform postorder traversal private void RecurPostOrder( TreeNode node ) if ( node == null ) return; RecurPostOrder( node.left ); RecurPostOrder( node.right ); System.out.print( node.data + " " );

Main Application for Binary Search Tree (primitive data type integer) import java.util.*; public class BinaryTreeApp { public static void main(String[] args) Scanner s = new Scanner(System.in); BSTree tree = new BSTree(); //insert 5 integer numbers into a binary search tree for(int i = 1; i <= 5; i++) System.out.println("Enter an integer number"); int n = s.nextInt(); tree.insertNode(n); }

//Traverse the binary search tree System.out.println("Inorder Traversal"); tree.InOrder(); System.out.println("Postorder Traversal"); tree.PostOrder(); System.out.println("Preorder Traversal"); tree.PreOrder(); }

public int totalOrder(String productCode) { return recurTotalOrder(root, productCode); } private int recurTotalOrder(TreeNode node, String productCode) if (node == null) return 0; else Order o = (Order) node.data; return 0.getOrder() + recurTotalOrder(node.left, productCode) + recurTotalOrder(node.right, productCode);

public int countHandphoneBrand(String brand) { return countHP(root, brand); } private int countHP(TreeNode node, String brand) if (node == null) return 0; else Handphone h = (Handphone) node.data; if (h.getBrand().equalsIgnoreCase(brand)) return 1 + countHP(node.left,brand) + countHP(node.right,brand); return countHP(node.left, brand) + countHP(node.right, brand);

public double calTotalPrice(String brand) { return calculateTotal (root, brand); } private double calculateTotal(TreeNode node, String brand) if (node == null) return 0; else Handphone h = (Handphone) node.data; if (h.getBrand().equalsIgnoreCase(brand)) return h.getPrice() + calculateTotal(node.left, brand) + calculateTotal(node.right, brand); return calculateTotal(node.left, brand) + calculateTotal(node.right, brand);

Public static void main(String[] args) { Scanner s = new Scanner(System.in); BSTHandphone Bst = new BSTHandphone(); for (int i=0; i<5;i++) int pNum = s.nextInt(); String brand = s.next(); double price = s.nextDouble(); String owner = s.next(); int year = s.nextInt(); Handphone h = new Handphone (pNum, brand, price, owner, year); Bst.insertData(h); } System.out.println(Bst.countHandphoneBrand(brand); System.out.println(Bst.calTotalPrice(brand); }}