Answer to Question #285345 in C++ for tayyaba

Question #285345

15. The nodes in a binary tree in preorder and inorder sequences are as follows: preorder: ABCDEFGHIJKLM inorder: CEDFBAHJIKGML


1
Expert's answer
2022-01-07T07:45:21-0500
#include <iostream>
using namespace std;
class BSTNode{
    public:
    char data;
    BSTNode *left_child, *right_child;
    BSTNode();
    BSTNode(char);
};
BSTNode::BSTNode(){
    left_child = NULL;
    right_child = NULL;
}
BSTNode::BSTNode(char data){
    this->data = data;
    left_child = NULL;
    right_child = NULL;
}
class BinaryTree{
    BSTNode* root;
    public:
    BinaryTree();
    void insert(char data);
    void insert(char data, BSTNode **parent);
    void inorder();
    void inorder(BSTNode *parent);
    void preorder();
    void preorder(BSTNode *parent);
};
BinaryTree::BinaryTree(){
    root = NULL;
}
void BinaryTree::insert(char data){
    insert(data, &root);
}
void BinaryTree::insert(char data, BSTNode** parent){
    if(*parent == NULL){
        BSTNode* temp = new BSTNode(data);
        *parent = temp;
        return;
    }
    if(data <= (*parent)->data) insert(data, &(*parent)->left_child);
    else insert(data, &(*parent)->right_child);
}


void BinaryTree::inorder(){
    inorder(root);
}
void BinaryTree::inorder(BSTNode *parent){
    if(parent == NULL) return;
    inorder(parent->left_child);
    cout<<parent->data<<" ";
    inorder(parent->right_child);
}
void BinaryTree::preorder(){
    preorder(root);
}
void BinaryTree::preorder(BSTNode *parent){
    if(parent == NULL) return;
    cout<<parent->data<<" ";
    preorder(parent->left_child);
    preorder(parent->right_child);
}


int main(){
    BinaryTree tree;
    string letters = "CEDFBAHJIKGML";
    for(int i = 0; i < letters.length(); i++){
        tree.insert(letters[i]);
    }


    cout<<"Preorder: ";
    tree.preorder();


    cout<<"\nInorder: ";
    tree.inorder();


    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