5. Tree
Binary tree
Recursive
Traversal
Traversal in trees and types
Conclusion
1. In-order
2. Post-order
3. Pre-order
6. A tree T is a set of nodes storing
elements such that the nodes have a
parent-child relationship
Root : The top node in the tree.
Leaves : Nodes having no children.
Height of a tree : length of the
longest path from the root to a
leaf.
height of this tree= 3
RL
N Root
7. Binary Trees
(Full Binary Trees)
Full Binary Tree: A full binary tree is a binary
tree where all the leaves are on the same
level and every non-leaf has two children.
The first four full binary trees are:
7
15. Traversal is the process of visiting every
node once in a tree.
Three techniques are used for traversing in trees
In-order
Post-order
Pre-order
16. 16
In-order Traversal:
1. Traverse left sub tree(LST)
2. Visit the root
3. Traverse right sub tree(RST)
Post-order Traversal:
1. Traverse left sub tree(LST)
2. Traverse right sub tree(RST)
3. Visit the root
Pre-order Traversal:
1. Visit the root
2. Traverse left sub tree (LST)
3. Traverse right sub tree(RST)
23. 23
void preOrder(Tree *tree)
{
if (tree->isEmpty( ))
return;
visit(tree->getRoot( ));
preOrder(tree->getLeftSubtree());
preOrder(tree->getRightSubtree());
}
Code for the Traversal
24. Code for the Traversal
void postOrder(Tree *tree)
{
if (tree->isEmpty( ))
return;
postOrder(tree->getLeftSubtree( ));
postOrder(tree->getRightSubtree( ));
visit(tree->getRoot( ));
}
25. void inOrder(Tree *tree)
{
if (tree->isEmpty( ))
return;
inOrder(tree->getLeftSubtree( ));
visit(tree->getRoot( ));
inOrder(tree->getRightSubtree( ));
}
Code for the Traversal
26. Traversal: In tree s a technique in which we search
elements “once”.
Three types of traversal used in trees are:
1. Post-order (root, Left sub tree, Right sub tree)
2. In-Order ( Left sub tree, Root, Right sub tree)
3. Pre-order(Left sub tree, Right sub tree, Root)