15. The nodes in a binary tree in preorder and inorder sequences are as follows: preorder: ABCDEFGHIJKLM inorder: CEDFBAHJIKGML
#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;
}
Comments