Binary Tree Lesson
Binary Tree Lesson
Binary Tree
NH
Binary Tree
A tree in which no node can have more than
two children
Root
TL
TR
Binary Tree
NH
Binary Tree
NH
+
a
a
a
+
c
*
a
b
a
c
+
c
d
*
e
Binary Tree
NH
Tree Traversal
An operation to trace nodes in the tree
PreOrder Traversal: (Recursive)
o Visit (and Print) root of the tree
o Visit Left SubTree of the root
o Visit Right SubTree of the root
InOrder Traversal: (Recursive)
o Visit Left SubTree of the root
o Visit (and print) root of the tree
o Visit Right SubTree of the root
PostOrder Traversal: (Recursive)
o Visit Left SubTree of the root
o Visit Right SubTree of the root
o Visit (and print) root of the tree
The Algrithm/Pseudo Code
struct Node{
datatype data;
Node *left,*right;
};
Node *root;
Binary Tree
PreOrder(Node *n)
{
if(n){
print(ndata);
PreOrder(nleft);
PreOrder(nright);
}
}
InOrder(Node *n)
{
if(n){
InOrder(nleft);
NH
print(ndata);
InOrder(nright);
}
}
PostOrder(Node *n)
{
if(n){
PostOrder(nleft);
PostOrder(nright);
print(ndata);
}
}
Binary Tree
NH
Exercises
1. Do preorder and postorder traversals on the tree
above.
2. How to implement binary tree using array?
Hints:
a. Index value of the array refers to node
number
b. Root must be in index value of 0
c. Tree with n nodes will have node number
starting from 0 to (n-1)
d. Position of left child of a node whose index
value p is (2p + 1)
e. Position of right child of a node whose index
value p is (2p + 2)
f. Position of parent of a node whose index value
p is (p 1)/2