xxxxxxxxxx
// C program for different tree traversals
#include <stdio.h>
#include <stdlib.h>
// A binary tree node has data, pointer to left child
// and a pointer to right child
struct node {
int data;
struct node* left;
struct node* right;
};
// Helper function that allocates a new node with the
// given data and NULL left and right pointers.
struct node* newNode(int data)
{
struct node* node
= (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
// Given a binary tree, print its nodes in inorder
void printInorder(struct node* node)
{
if (node == NULL)
return;
// First recur on left child
printInorder(node->left);
// Then print the data of node
printf("%d ", node->data);
// Now recur on right child
printInorder(node->right);
}
// Driver code
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Function call
printf("Inorder traversal of binary tree is \n");
printInorder(root);
getchar();
return 0;
}
xxxxxxxxxx
//*******this is a C program for implementation and searching in A BT*******
#include<stdlib.h>
#include <stdio.h>
struct BinaryTree{
int data;
struct BinaryTree*right;
struct BinaryTree*left;
};
struct BinaryTree*createnode(int val){
struct BinaryTree*root=(struct BinaryTree*)malloc(sizeof(struct BinaryTree));
root->data=val;
root->left=NULL;
root->right=NULL;
}
void inorder(struct BinaryTree*root){
if(root==NULL){
return;
}
else {inorder(root->left);
printf("%d->",root->data);
inorder(root->right);
}
}
void preorder(struct BinaryTree*root){
if(root==NULL){
return;
}
else {
printf("%d->",root->data);
preorder(root->left);
preorder(root->right);
}
}
void postorder(struct BinaryTree*root){
if(root==NULL){
return;
}
else{
postorder(root->left);
postorder(root->right);
printf("%d->",root->data);
}
}
int main()
{
printf("Lets grow the tree\n");
struct BinaryTree*root=createnode(1);
root->left=createnode(2);
root->right=createnode(3);
root->left->left=createnode(4);
root->left->right=createnode(5);
printf("tree has grown up\n");
printf("Inorder traversal ");
inorder(root);printf("NULL");
printf("\npreorder traversal ");
preorder(root);printf("NULL");
printf("\nPostorder traversal");
postorder(root);printf("NULL");
return 0 ;
}
xxxxxxxxxx
Until all nodes are traversed −
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.
xxxxxxxxxx
def inOrder(root):
if root:
inOrder(root.left)
print(root, end = " ")
inOrder(root.right)