#include<bits/stdc++.h>
using namespace std;
class node{
public:
int val;
node*left;
node*right;
node(int data){
val=data;
left=NULL;
right=NULL;
}
};
void insert(node*&root,int val){
queue<node*>q;
if(!root){
root=new node(val);
return ;
}
q.push(root);
while(!q.empty()){
node*temp=q.front();
q.pop();
if(temp->left)q.push(temp->left);
else{
temp->left=new node(val);
return;
}
if(temp->right) q.push(temp->right);
else{
temp->right=new node(val);
return;
}
}
}
void show(node*root){
queue<node*>q;
if(root) q.push(root);
else return;
while(!q.empty()){
node*temp=q.front();
q.pop();
cout<<temp->val<<" ";
if(temp->left) q.push(temp->left);
if(temp->right)q.push(temp->right);
}
cout<<endl;
}
int main(){
node*root=NULL;
insert(root,10);
insert(root,20);
show(root);
insert(root,30);
insert(root,40);
show(root);
}
No comments:
Post a Comment