Download presentation
Presentation is loading. Please wait.
1
BINARY TREE CSC248 – Data Structure
2
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.
3
What is a TREE? Examples of a tree structure
4
Tree Terminology
5
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.
6
What is a BINARY TREE? Examples of a binary tree data structure
7
Graphical Representation of Binary Tree
8
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 = leaf Example
9
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
10
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.
11
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.
12
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.
13
EXERCISE Identify the type of the following tree diagram:
14
EXERCISE Determine whether the following tree is a binary tree
15
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)
16
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 :
17
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
18
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
19
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
20
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.
21
Building the Expression Tree
22
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.
23
Using Postfix Expression
24
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
25
Traverse the tree in inorder, preorder and postorder
26
INORDER TRAVERSAL The traversal result is: * 2 -1
27
PREORDER TRAVERSAL The traversal result: - + 3 * 7 2 1
28
Post-order traversal The traversal result: 3 7 2 * + 1 -
29
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
30
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
31
//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 );
32
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)
33
// 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 ); }
34
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 );
35
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 );
36
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 + " " );
37
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); }
38
//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(); }
39
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);
40
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);
41
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);
42
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); }}
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.