Reputation: 73
This code runs on ideone and other compilers but gives segmentation fault in my mac or some junk values. Please help. This is standard in order traversal and should just print 1 to 7.
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
typedef struct node* Node;
Node insert(Node root, int num){
if(root==NULL){
Node newNode=(Node)malloc(sizeof(Node));
newNode->data=num;
newNode->left=NULL;
newNode->right=NULL;
return newNode;
}
if(root->data>num)
root->left=insert(root->left,num);
else
root->right=insert(root->right,num);
return root;
}
void printinorder(Node root){
if(root==NULL)
return;
printinorder(root->left);
cout<<root->data<<endl;
printinorder(root->right);
}
int main(){
Node tree=NULL;
tree=insert(tree,1);
tree=insert(tree,2);
tree=insert(tree,3);
tree=insert(tree,4);
tree=insert(tree,5);
tree=insert(tree,6);
tree=insert(tree,7);
printinorder(tree);
}
Upvotes: 1
Views: 147
Reputation: 6125
Node newNode = (Node) malloc(sizeof(Node));
should be
Node newNode = (Node) malloc(sizeof(node));
Upvotes: 5