Created
August 18, 2019 07:19
-
-
Save manojnaidu619/19da83ed882d94ffc3ab3037de805197 to your computer and use it in GitHub Desktop.
Binary Tree creation in CPP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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