This is a C Program to print the double order traversal of the given tree.
Recurse through:
1. Visit root of (sub)tree.
2. Visit left sub-tree.
3. Revisit root of (sub)tree.
4. Visit right sub-tree.
Recurse through:
1. Visit root of (sub)tree.
2. Visit left sub-tree.
3. Revisit root of (sub)tree.
4. Visit right sub-tree.
Here is source code of the C Program to Implement Double Order Traversal of a Binary Tree. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#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 doubleorder*/
void printDoubleorder(struct node* node) {
if (node == NULL)
return;
/* first print data of node */
printf("%d ", node->data);
/* then recur on left sutree */
printDoubleorder(node->left);
/* first print data of node */
printf("%d ", node->data);
/* now recur on right subtree */
printDoubleorder(node->right);
}
/* Driver program to test above functions*/
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);
printf("\n Doubleorder traversal of binary tree is \n");
printDoubleorder(root);
getchar();
return 0;
}
Output:
$ gcc Doubleorder.c $ ./a.out Preorder traversal of binary tree is 1 2 4 4 2 5 5 1 3 3
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Related Posts:
- Practice Design & Analysis of Algorithms MCQ
- Check Computer Science Books
- Practice Computer Science MCQs
- Apply for Computer Science Internship
- Check Programming Books