here I wrote my own binary search tree using C++, but when I tried to insert left or right node it doesn't work at all..
what's wrong with it. I can't figured out
Moderators note : used code tags
what's wrong with it. I can't figured out
C:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *r, *l;
}Tree;
typedef struct Node* T_ptr;
T_ptr newnode(int val) {
T_ptr T;
T = (T_ptr)malloc(sizeof(Tree));
T->data = val;
T->l = NULL;
T->r = NULL;
return T;
}
void insertnode(T_ptr root,int v) {
if (root == NULL) { //base case
root = newnode(v);
}
else { //recursive
if (v >= root->data) {
insertnode(root->r,v);
}
if (v <= root->data) {
insertnode(root->l, v);
}
}
}
void inorder(T_ptr root) {
if (root == NULL) return;
printf("Inorder traverse : ");
inorder(root->l);
printf("%d ",root->data);
inorder(root->r);
printf("\n");
}
void main() {
T_ptr root=NULL;
int dt;
while (true) {
printf("please enter val : ");
scanf("%d", &dt);
if (root == NULL)
root = newnode(dt);
else
insertnode(root, dt);
inorder(root);
}
}
Last edited by a moderator: