this is a code to insert data into a binary tree but it exceed time limit , input would be as follows
First line contains two integers, T and X, number of nodes in the tree and value of the root.
Each detail of node contains two lines. First lines contains a string and second line contains an integer, which denotes the path of the node and the value of the node respectively.
String consists of only L or R. L denotes left child and R denotes right child
5 1
L
2
R
3
LL
4
LR
5
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int x;
Node*left,*right;
Node(int data){
x=data;
left=NULL;
right=NULL;
}
};
void insert(Node*root,string s,int data)
{
if(root==NULL) return;
if(s[0]=='L')
{
root->left->x=data;
root=root->left;
return;
}
if(s[0]=='R'){
root->right->x=data;
root=root->right;
return;
}
else
insert(root,s.substr(1),data);
}
void preorder(Node*root){
cout<<root->x<<" ";
preorder(root->left);
preorder(root->right);
}
int main()
{
int n,x;
cin>>n>>x;
Node*root=new Node(x);
while(n--)
{
string s; cin>>s;
int data; cin>>data;
insert(root,s,data);
}
preorder(root);
}
Aucun commentaire:
Enregistrer un commentaire