Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Created August 18, 2019 07:19
Show Gist options
  • Save manojnaidu619/19da83ed882d94ffc3ab3037de805197 to your computer and use it in GitHub Desktop.
Save manojnaidu619/19da83ed882d94ffc3ab3037de805197 to your computer and use it in GitHub Desktop.
Binary Tree creation in CPP
#include <iostream>
#include <queue>
using namespace std;
struct Node {
int data;
struct Node * left;
struct Node * right;
}*root=NULL;
int main(){
queue<Node*> q;
int left,right,ele;
struct Node *node, *temp;
cout << "Enter root data : ";
cin >> ele;
if(ele != -1){
root = new Node;
root -> data = ele;
root -> left = NULL;
root -> right = NULL;
q.push(root);
}
while(!q.empty()){
node = q.front();
q.pop();
cout << "Enter left child of " << node->data << ": ";
cin>>left;
if(left!=-1){
temp = new Node;
temp->data = left;
temp->left = NULL;
temp->right = NULL;
node -> left = temp;
q.push(temp);
}
cout << "Enter right child of " << node->data << ": ";
cin>>right;
if(right!=-1){
temp = new Node;
temp->data = right;
temp->left = NULL;
temp->right = NULL;
node -> right = temp;
q.push(temp);
}
}
// Any Tree Traversal methods can be called..
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment