Sei sulla pagina 1di 39

4 Binary Trees

Data Structures Binary Trees 1


Objectives
At 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

Data Structures Binary Trees 2


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 theroot


Data Structures Binary Trees 3
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
Data Structures Binary Trees 4
Binary Tree

Data Structures Binary Trees 5


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

Data Structures Binary Trees 6


Types

right (left) skewed binary tree - tree in which every nodehas


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

Data Structures Binary Trees 7


Types

strictly binary tree - tree in which every node has eithertwo


subtrees or none at all

Data Structures Binary Trees 8


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

Data Structures Binary Trees 9


Types

complete binary tree - tree which results when zero or more


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

Data Structures Binary Trees 10


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;
} }

Data Structures Binary Trees 11


Representation

Data Structures Binary Trees 12


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

Data Structures Binary Trees 13


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.

Data Structures Binary Trees 14


Traversals

Preorder traversal NLR traversal

EASY
procedure PREORDER(T)
node(LSON, DATA, RSON)
if T <> then [
output DATA(T)
call PREORDER(LSON(T))
call PREORDER(RSON(T))]
end PREORDER

JAVA
/* 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();
}
}
Data Structures Binary Trees 15
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.

Data Structures Binary Trees 16


Traversals

Inorder traversal LNR traversal


EASY
procedure INORDER(T)
node(LSON, DATA, RSON)
if T <> then [
call INORDER(LSON(T))
output DATA(T)
call INORDER(RSON(T)) ]
end INORDER

JAVA
/* 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();
}
}
Data Structures Binary Trees 17
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.

Data Structures Binary Trees 18


Traversals

Postorder traversal LRN traversal


EASY
procedure POSTORDER(T)
node(LSON, DATA, RSON)
if T <> then [
call POSTORDER(LSON(T))
call POSTORDER(RSON(T))
output DATA(T)]
end POSTORDER

JAVA
/* 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());
}
}

Data Structures Binary Trees 19


Traversals
OCCURENCES 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

Data Structures Binary Trees 20


Traversal Examples

Data Structures Binary Trees 21


Traversal Examples

Data Structures Binary Trees 22


Traversal Application
Duplicating 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

Data Structures Binary Trees 23


Traversal Application
Duplicating a Binary Tree
procedure COPY(T)
// Given a binary tree T, COPY makes a duplicate copy of T and returns
a pointer to the root node of the constructed copy //
node (LSON, DATA, RSON)

if T <> then [ beta COPY(LSON(T)); sigma COPY(RSON(T))
call GETNODE(); DATA() DATA(T)
LSON() beta; RSON() sigma ]
return( ) EASY
end COPY

/* 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;
} JAVA
return null;
} Data Structures Binary Trees 24
Traversal Application
Equivalence 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

Data Structures Binary Trees 25


Traversal Application
Equivalence of Two Binary Trees
procedure EQUIV(S, T)
// Given two binary trees S and T, EQUIV returns true if S and T are
equivalent; else false is returned. //
node (LSON, DATA, RSON)
ans false
case
: S = and T = : ans true
: S <> and T <> : [ ans (DATA(S) = DATA(T))
if ans then ans EQUIV(LSON(S), LSON(S))
if ans then ans EQUIV(RSON(S), RSON(S)) ]
endcase
return(ans)
end EQUIV

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));}
if (answer) { answer = new BinaryTree(root.right);
equivalent(new BinaryTree(t2.root.right)); }
return answer;
} Data Structures Binary Trees 26
Exercises

Tree 2

Tree 1

Tree 3

Data Structures Binary Trees 27


This page is intentionally left blank

Data Structures Binary Trees 28


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

Data Structures Binary Trees 29


Heaps

Data Structures Binary Trees 30


Sequential Representation

Complete binary tree

Data Structures Binary Trees 31


Sequential Representation
Properties 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 /

Data Structures Binary Trees 32


Heaps and Sift-Up
Sift-Up - bottom-up, right-to-left process of converting a complete
binary tree into a heap
Example

Data Structures Binary Trees 33


Sift-Up
EASY Code
procedure SIFT-UP(i, n)
//Converts an almost-heap on n nodes and rooted at node
i into a heap//
array KEY(1:n)
k <-- KEY(i) //keep key at root of almost-heap//
j <-- 2*i //find left son of root//
while j n do
if j < n and KEY(j+1) > KEY(j) then j <-- j+1
//larger key migrates upward//
if KEY(j) > k then [ KEY(i) <-- KEY(j)
i <-- j //root of next subtree//
j <-- 2*i] //left son of new root//
else exit
endwhile
KEY(i) <-- k
//root key finds final resting place//
end SIFT-UP

Data Structures Binary Trees 34


Sift-Up
Java Code
/* 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 */
} Data Structures Binary Trees 35
Heapsort
Heapsort algorithm put forth in 1964 by R. W. Floyd and J. W.
J. Williams
1. 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.

Data Structures Binary Trees 36


Heapsort
EASY Code
procedure HEAPSORT(K, n)
//Performs an in-place sort of the keys in O(nlog2n) time //

array K(1:n)

//Convert K into an almost-heap//


for i <-- n/2 to 2 by -1 do
call SIFT-UP(i, n)
endfor

//Sift-up to root, exchange root and last leaf, and consider last
leaf deleted from binary tree and entered into output queue//
for j <-- n to 2 by -1 do
call SIFT-UP(1, j) //Sift-up to root//
K(i) <--> K(j) //Exchange root and last leaf//
endfor
end HEAPSORT

Data Structures Binary Trees 37


Heapsort
Java Code
/* 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;
}
} Data Structures Binary Trees 38
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

Data Structures Binary Trees 39

Potrebbero piacerti anche