A leaf node is the root node of an empty tree.
Each node can have two children at most.
Implementation:
Use dynamic memory allocation to create and destroy
nodes when required.
Eg. struct node { DataType data;
node *right;
node *left;
};
We require a pointer variable to hold the address of the root node. node *root = 0; // empty treeAll other nodes are accessed by traversing the tree until they are located.
eg. non empty tree.
Expression trees
An inorder traversal will visit each node of the tree by ascending order of the node data.
void PreOrderTraversal( treenode *ptr )
{
if (ptr !=0){
cout << ptr->data << endl;
PreOrderTraversal( ptr->left );
PreOrderTraversal( ptr->right);
}
}
void PostOrderTraversal( treenode *ptr )
{
if (ptr !=0){
PostOrderTraversal( ptr->left );
PostOrderTraversal( ptr->right);
cout << ptr->data << endl;
}
}
void InOrderTraversal( treenode *ptr )
{
if (ptr!=0){
InOrderTraversal( ptr->left );
cout << ptr->data << endl;
InOrderTraversal( ptr->right);
}
}
// level_by_level trversal of a binary tree
// Mal Sutherland 1995
#include <iostream.h>
#include "queue.h"
struct treenode {
char data;
treenode *left;
treenode *right;
};
typedef treenode* treeptr; // variables of type treeptr contain
// an address of a treenode.
void build_tree (treeptr & root);
void main ()
{
Queue<treeptr> Q; // A queue of pointers to treenodes
treeptr ptr; // temporary pointer to a treenode
treeptr root = 0; // Contains the address of the root node
build_tree(root); // Builds a binary tree
ptr = root; // start traversal from the root node
if ( ptr != 0 ){ // only do traversal if tree is not empty
Q.enqueue(ptr); // put address of current node onto Q
while ( !Q.isEmpty() ) // While there are nodes to visit
{
Q.dequeue( ptr ); // current node = front from Q
cout << ptr->data << endl; // visit node
if ( ptr->left != 0 ) // if current node has a left child
Q.enqueue(ptr->left); // put address of child onto Q
// end if
if ( ptr->right != 0 ) // if current node has a right child
Q.enqueue(ptr->right); // put address of child onto Q
// end if
} // end while
}
}
M
/ \
D P
/ / \
B N Z
/ \ \
A C O
preorder traversal = M,D,B,A,C,P,N,O,ZAn inorder traversal will visit each node of the tree by ascending order of the node data.
We require a pointer variable to hold the address of the root node.node *root = 0; // empty treeAll other nodes are accessed by traversing the tree until they are located.