Answer to Question #247723 in C++ for rohit

Question #247723

Note: No code is required.


Consider the following tree


root=A


root->left=B


root->left->left=C


root->left->left->right=D


root->left->right=E


root->left->right->right=H


root->left->right->left=F


root->left->right->left->right=G


root->right=I


root->right->left=J


root->right->left->left=K


root->right->right=L


root->right->right->right=N


root->right->right->left=M




Task :


Write down the following for the above tree


1)In Order Traversal


2)Pre Order Traversal


3)Post Order Traversal


1
Expert's answer
2021-10-08T19:12:43-0400
#include <iostream>

struct Node {
    char value;
    struct Node *left, *right;
    // constructor
    Node(char value) {
        this->value = value;
    }
};

void inOrderTraversal(struct Node *root) {
    if (root->left) inOrderTraversal(root->left);
    std::cout << root->value << " ";
    if (root->right) inOrderTraversal(root->right);
}

void preOrderTraversal(struct Node *root) {
    std::cout << root->value << " ";
    if (root->left) inOrderTraversal(root->left);
    if (root->right) inOrderTraversal(root->right);
}

void postOrderTraversal(struct Node *root) {
    if (root->left) inOrderTraversal(root->left);
    if (root->right) inOrderTraversal(root->right);
    std::cout << root->value << " ";
}

int main() 
{
    Node *root = new Node('A');
    root->left = new Node('B');
    root->left->left = new Node('C');
    root->left->left->right = new Node('D');
    root->left->right = new Node('E');
    root->left->right->right = new Node('H');
    root->left->right->left = new Node('F');
    root->left->right->left->right = new Node('G');
    root->right = new Node('I');
    root->right->left = new Node('J');
    root->right->left->left = new Node('K');
    root->right->right = new Node('L');
    root->right->right->right = new Node('N');
    root->right->right->left = new Node('M');
    
    inOrderTraversal(root);
    std::cout << std::endl;
    preOrderTraversal(root);
    std::cout << std::endl;
    postOrderTraversal(root);
    
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS