MELJUN CORTES Jedi slides data st-chapter04-binary trees

Post on 22-Jun-2015

689 views 3 download

Tags:

description

MELJUN CORTES Jedi slides data st-chapter04-binary trees

Transcript of MELJUN CORTES Jedi slides data st-chapter04-binary trees

1Data Structures – Binary Trees

4 Binary Trees

2Data Structures – Binary Trees

ObjectivesAt the end of the lesson, the student should be able to:● Explain the basic concepts and definitions related to binary

trees● Identify the properties of a binary tree● Enumerate the different types of binary trees● Discuss how binary trees are represented in computer

memory ● Traverse binary trees using the three traversal algorithms:

preorder, inorder, postorder● Discuss binary tree traversal applications● Use heaps and the heapsort algorithm to sort a set of

elements

3Data Structures – Binary Trees

Binary Tree● An ADT that is hierarchical in nature● Collection of nodes which are either empty or consists of a

root and two disjoint binary trees called the left and the right subtrees

● Level of a node - distance of the node from the root

4Data Structures – Binary Trees

Binary Tree● Height or depth of a tree - level of the bottommost nodes;

length of the longest path from the root to any leaf

● External node - node w/o children; internal otherwise● Proper binary tree - binary tree that has either zero or two

children

5Data Structures – Binary Trees

Binary Tree●

6Data Structures – Binary Trees

Properties● For a (proper) binary tree of depth k,

– The maximum number of nodes at level i is 2i , i ≥ 0

– The number of nodes is at least 2k + 1 and at most 2k+1 – 1

– The number of external nodes is at least h+1 and at most 2k

– The number of internal nodes is at least h and at most 2k – 1

– If no is the number of terminal nodes and n2 is the number of nodes of degree 2 in a binary tree, then no = n2 + 1

7Data Structures – Binary Trees

Types● right (left) skewed binary tree - tree in which every node

has no left (right) subtrees; tree with the greatest depth

8Data Structures – Binary Trees

Types● strictly binary tree - tree in which every node has either

two subtrees or none at all

9Data Structures – Binary Trees

Types● full binary tree - strictly binary tree in which all terminal

nodes lie at the bottom-most level; has the maximum number of nodes for a given depth

10Data Structures – Binary Trees

Types● complete binary tree - tree which results when zero or

more nodes are deleted from a full binary tree in reverse-level order

11Data Structures – Binary Trees

Representation● Link Representation

class BTNode {Object info;BTNode left, right;public BTNode(){}

public BTNode(Object i) {info = i;

}public BTNode(Object i, BTNode l, BTNode r) {

info = i;left = l;right = r;

} }

12Data Structures – Binary Trees

Representation●

13Data Structures – Binary Trees

Traversals

● A procedure that visits the nodes of the binary tree in a linear fashion such that each node is visited exactly once, visit a node means performing computations local to the node

● Preorder● Inorder● Postorder

14Data Structures – Binary Trees

Traversals● Preorder traversal – NLR traversal

If the binary tree is empty, do nothing (traversal done)Otherwise:

Visit the root.Traverse the left subtree in preorder.Traverse the right subtree in preorder.

15Data Structures – Binary Trees

Traversals● Preorder traversal – NLR traversal

/* Outputs the preorder listing of elements in this tree */ void preorder(){

if (root != null) { System.out.println(root.info.toString()); new BinaryTree(root.left).preorder(); new BinaryTree(root.right).preorder();

} }

16Data Structures – Binary Trees

Traversals● Inorder traversal – LNR traversal

If the binary tree is empty, do nothing (traversal done)Otherwise:

Traverse the left subtree in inorder.Visit the root.Traverse the right subtree in inorder.

17Data Structures – Binary Trees

Traversals● Inorder traversal – LNR traversal/* Outputs the inorder listing of elements in this tree */

void inorder(){ if (root != null) {

new BinaryTree(root.left).inorder(); System.out.println(root.info.toString());new BinaryTree(root.right).inorder();

}}

18Data Structures – Binary Trees

Traversals● Postorder traversal – LRN traversal

If the binary tree is empty, do nothing (traversal done)Otherwise:

Traverse the left subtree in postorder.Traverse the right subtree in postorder.Visit the root.

19Data Structures – Binary Trees

Traversals● Postorder traversal – LRN traversal/* Outputs the postorder listing of elements in this tree */

void postorder(){ if (root != null) {

new BinaryTree(root.left).postorder(); new BinaryTree(root.right).postorder(); System.out.println(root.info.toString());

} }

20Data Structures – Binary Trees

TraversalsOCCURENCES OF VISITS

● Preorder and Inorder:– On going down leftward as its left subtree is traversed– On going up from the left after its left subtree is traversed

● Postorder: – On going down leftward as its left subtree is traversed– On going up from the left after its left subtree has been traversed– On going up from the right after its right subtree has been traversed

21Data Structures – Binary Trees

Traversal Examples

22Data Structures – Binary Trees

Traversal Examples

23Data Structures – Binary Trees

Traversal ApplicationDuplicating a Binary Tree

● The Algorithm

● Traverse the left subtree of node a in postorder and make a copy of it ● Traverse the right subtree of node a in postorder and make a copy of it● Make a copy of node a and attach copies of its left and right subtrees

24Data Structures – Binary Trees

Traversal ApplicationDuplicating a Binary Tree

/* Copies this tree and returns the root of the duplicate */

BTNode copy(){BTNode newRoot;BTNode newLeft;BTNode newRight;if (root != null){

newLeft = new BinaryTree(root.left).copy();newRight = new BinaryTree(root.right).copy(); newRoot = new BTNode(root.info, newLeft, newRight);

return newRoot;} return null;

}

25Data Structures – Binary Trees

Traversal ApplicationEquivalence of Two Binary Trees

● The Algorithm

● Check whether node a and node b contain the same data● Traverse the left subtrees of node a and node b in preorder and check

whether they are equivalent● Traverse the right subtrees of node a and node b in preorder and

check whether they are equivalent

26Data Structures – Binary Trees

Traversal ApplicationEquivalence of Two Binary Trees

boolean equivalent(BinaryTree t2){boolean answer = false;if ((root == null) && (t2.root == null))

answer = true;else {

answer = (root.info.equals(t2.root.info));if (answer) {

answer = new BinaryTree(root.left);equivalent(new BinaryTree(t2.root.left));

}equivalent(new BinaryTree(t2.root.right));

}return answer;

}

27Data Structures – Binary Trees

Exercises

Tree 1

Tree 2

Tree 3

28Data Structures – Binary Trees

Binary Tree Application: Heaps and Heapsort

● Heaps– complete binary tree that has elements stored at its nodes– satisfies the heap-order property: for every node u except the root,

the key stored at u is less than or equal to the key stored at its parent

– In this application, elements stored in a heap satisfy the total order: For any objects x, y and z in set S:

● Transitivity: if x < y and y < z then x < z● Trichotomy: for any two objects x and y in S, exactly one of these

relations holds: x > y, x = y or x < y

29Data Structures – Binary Trees

Heaps●

30Data Structures – Binary Trees

Sequential Representation● Complete binary tree

31Data Structures – Binary Trees

Sequential RepresentationProperties of a heap represented as a complete binary tree:

● If 2i ≤ n, the left son of node i is 2i; otherwise, node i has no left son

● If 2i < n (2i + 1 ≤ n in Java), the right son of node i is 2i + 1; otherwise, node i has no right son

● If 1 < i ≤ n, the father of node i is (i)/2

32Data Structures – Binary Trees

Heaps and Sift-Up – Sift-Up - bottom-up, right-to-left process of converting a complete

binary tree into a heap– Example

33Data Structures – Binary Trees

Sift-UpJava Implementation

● /* Converts an almost-heap on n nodes rooted at i into a heap */● public void siftUp (int i, int n) {

– int k = key[i]; /* keep key at root of almost-heap */– int child = 2 * i; /* left child */– while (child <= n) {

● if (child < n && key[child+1]> key[child]) child++ ;● /* if heap property is not satisfied */● if (key[child] > k){

– key[i] = key[child] ; /* Move the child up */– i = child ;– child = 2 * i; /*Consider the left child again*/

– } else break;

– }– key[i] = k ; /* this is where the root belongs */

– }

34Data Structures – Binary Trees

Heapsort ● Heapsort algorithm put forth in 1964 by R. W. Floyd and J.

W. J. Williams1. Assign the keys to be sorted to the nodes of a complete binary tree.

2. Convert this binary tree into a heap by applying sift-up to its nodes in reverse level order.

3. Repeatedly do the following until the heap is empty:

a)Remove the key at the root of the heap (the smallest in the heap) and place it in the output.

b)Detach from the heap the rightmost leaf node at the bottommost level, extract its key, and store this key at the root of the heap.

c)Apply sift-up to the root to convert the binary tree into a heap once again.

35Data Structures – Binary Trees

HeapsortJava Implementation

– /* Performs an in-place sort of the keys in O(nlog2n) time */public void sort(){

int n = key.length-1;

● /* Convert key into almost-heap */● for (int i=n/2; i>1; i--){

– siftUp(i, n);● }●

● /* Exchange the current largest in key[1] with key[i] */● for (int i=n; i>1; i--){

– siftUp(1, i);– int temp = key[i];– key[i] = key[1];– key[1] = temp;

● }– }

36Data Structures – Binary Trees

Summary● A binary tree is an abstract data type that is hierarchical in

structure● A binary tree could be classified as skewed, strict, full or complete● Link representation is the most natural way to represent a binary

tree ● Three ways to traverse a tree are preorder, inorder, and postorder● Binary tree traversals could be used in applications such as

duplication of a binary tree and checking the equivalence of two binary trees

● The heapsort algorithm utilizes the heap ADT and runs in O(n lg n) time