4 - Binary Trees
4 - Binary Trees
Proper binary tree - binary tree that has either zero or two
children
Data Structures Binary Trees 4
Binary Tree
Link Representation
class BTNode {
Object info;
BTNode left, right;
public BTNode(){}
public BTNode(Object i) {
info = i;
}
Preorder
Inorder
Postorder
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
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
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());
}
}
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
The Algorithm
The Algorithm
Tree 2
Tree 1
Tree 3
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
} 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.
array K(1:n)
//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