Ds 10 Binary Tree
Ds 10 Binary Tree
E C
D
K F G
H
L
M I
J
Samples of Trees
A A Complete Binary Tree
A
B B
Skewed Binary Tree
C B C
D
D E F G
E
H I
Maximum Number of Nodes in BT
The maximum number of nodes on level i of a
binary tree is 2i, i>=0.
A A
B C B C
D E F G D E F G
H I J K L M N O
H I
Complete binary tree Full binary tree of depth 4
Complete Binary Tree
If a complete binary tree with n nodes
(depth=└log n + 1┘)
is represented sequentially,
then for any node with index i, 1<=i<=n, we have:
parent(i) is at └i/2┘ if i!=1. If i=1, i is at the root and
has no parent.
leftChild(i) is at 2i if 2i<=n. If 2i>n, then i has no
left child.
rightChild(i) is at 2i+1 if 2i+1<=n. If 2i+1>n,
then i has no right child.
Extended Binary Tree
A binary tree T is said to be a 2-tree or an extended binary tree if each
node N has either 0 or 2 children.
The nodes with 2 children are called internal nodes.
The nodes with o children are called external nodes.
B C
B C
D F
D F
G
Fig: Binary Tree T Fig: Extended 2-tree
[1] A
Sequential [2]
[3]
B
C
Representation
[1] A A
(1) waste space
(2) insertion/deletion
[4] D
[5] E
[2] B problem
[6] F
[3] --
B [7] G
[4] C A [8] H
[5] --
C [9] I
[6] --
[7] -- B C
D [8] D
[9] --
E . . D E F G
[16] E
H I
Linked Representation
struct btnode {
int data;
btnode *left, *right;
};
data
left right
Binary Tree Traversals
There are three standard ways of traversing a
binary tree T with root R.
These three algorithms, called:
preorder
inorder
postorder
Arithmetic Expression Using BT
+ preorder traversal
+**/ABCDE
prefix expression
* E
inorder traversal
* D A/B*C*D+E
infix expression
/ C
postorder traversal
AB/C*D*E+
A B postfix expression
Preorder Traversal (recursive
version)
Algorithm:
1. Process the root R.
2. Traverse the left subtree of R in preorder.
3. Traverse the right subtree of R in preorder.
+**/ABCDE
Pseudo-Code:
void preorder(btnode ptr)
/* preorder tree traversal */
{
if (ptr!=NULL) {
cout<<ptr->data;
preorder(ptr->left);
predorder(ptr->right);
}
}
Inorder Traversal (recursive version)
Algorithm:
1. Traverse the left subtree of R in inorder.
2. Process the root R.
3. Traverse the right subtree of R in inorder.
A/B*C*D+E
Pseudo-Code:
void inorder(btnode ptr)
/* inorder tree traversal */
{
if (ptr!=NULL) {
inorder(ptr->left);
cout<<ptr->data;
indorder(ptr->right);
}
}
Postorder Traversal (recursive version)
Algorithm:
1. Traverse the left subtree of R in postorder.
2. Traverse the right subtree of R in postorder.
3. Process the root R.
AB/C*D*E+
Pseudo-Code:
void postorder(btnode ptr)
/* postorder tree traversal */
{
if (ptr!=NULL) {
postorder(ptr->left);
postorder(ptr->right);
cout<<ptr->data;
}
}