Bloomberg LP Interview Question
Financial Software DevelopersCountry: United States
Interview Type: Phone Interview
How about this one? Since once mention the Btree I always think of recursive
struct node{
int data;
node *leftch;
node *rightch;
};
void intoatree(struct node **root, int n){
node *temp=new node;
(*temp).data=n;
(*temp).leftch=NULL;
(*temp).rightch=NULL;
node **par;
par=root;
if(*root==NULL){
*root=temp; //insert as the first node
}
else if((*(*par)).data==n){
cout<<"duplicate input"<<endl;
return;
}
else if((*(*par)).data>n){
*par=(*(*par)).leftch;
intoatree(par,n);
}
else{
*par=(*(*par)).rightch;
intoatree(par,n);
}
}
how about this?
TreeNode* insertNode(TreeNode *root, TreeNode *newNode) {
if (root == NULL) {
// if there is no root, use current one as root
return newNode;
}
if (newNode->val >= root->val) {
root->right = insertNode(root->right, newNode);
} else {
root->left = insertNode(root->left, newNode);
}
return root;
}
- Amit Khatri August 03, 2013