Implement inorder, preorder and postorder traversal methods in binary search tree in C++
Code
// Binary Search Tree operations in C++#include <iostream>using namespace std;struct node {int key;struct node *left, *right;};// Create a nodestruct node *newNode(int item) {struct node *temp = (struct node *)malloc(sizeof(struct node));temp->key = item;temp->left = temp->right = NULL;return temp;}// Inorder Traversalvoid inorder(struct node *root) {if (root != NULL) {// Traverse leftinorder(root->left);// Traverse rootcout << root->key << " -> ";// Traverse rightinorder(root->right);}}// preorder Traversalvoid preorder(struct node *root) {if (root != NULL) {// Traverse rootcout << root->key << " -> ";// Traverse leftpreorder(root->left);// Traverse rightpreorder(root->right);}}// postorder Traversalvoid postorder(struct node *root) {if (root != NULL) {// Traverse leftpostorder(root->left);// Traverse rightpostorder(root->right);// Traverse rootcout << root->key << " -> ";}}// Insert a nodestruct node *insert(struct node *node, int key) {// Return a new node if the tree is emptyif (node == NULL) return newNode(key);// Traverse to the right place and insert the nodeif (key < node->key)node->left = insert(node->left, key);elsenode->right = insert(node->right, key);return node;}// Driver codeint main() {struct node *root = NULL;root = insert(root, 8);root = insert(root, 3);root = insert(root, 1);root = insert(root, 6);root = insert(root, 7);root = insert(root, 10);root = insert(root, 14);root = insert(root, 4);cout << "Inorder traversal: "<< endl;inorder(root);cout << endl << "Preorder traversal: "<< endl;preorder(root);cout << endl << "Postorder traversal: "<< endl;postorder(root);cout << endl;return 0;}
Output
Inorder traversal:
1 -> 3 -> 4 -> 6 -> 7 -> 8 -> 10 -> 14 ->
Preorder traversal:
8 -> 3 -> 1 -> 6 -> 4 -> 7 -> 10 -> 14 ->
Postorder traversal:
1 -> 4 -> 7 -> 6 -> 3 -> 14 -> 10 -> 8 ->
0 Comments
Post a Comment