I am trying to learn recursion, so I tried one program to create a complete binary tree and then print the sum of all its elements, I wrote the insertion part myself and I am confused that my pointer variable "curr"
which points to a tree node, why I am able to do "curr = curr->left"
as it is just a pointer to a node. shouldn't only the actual tree node contain these left and right fields ? Just give me a heads up on this novice doubt. I am surprised that my program does the job though.
Thanks :)
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *left,*right;
};
struct node *head = NULL;
struct node *curr = NULL;
void insert_Data(int val,struct node* curr){
struct node *tempnode = (struct node*)malloc(sizeof(struct node));
tempnode->data = val;
tempnode->left = NULL;
tempnode->right = NULL;
if(head==NULL){
head = tempnode;
curr = head;
printf("head element is : %d\n",head->data);
}
else{
if(curr->left == NULL){
curr->left = tempnode;
}
else if(curr->right == NULL){
curr->right = tempnode;
}
else{
curr = curr->left;
insert_Data(val,curr);
}
}
}
//to test program
int sumNode(struct node* root ) {
// if there is no tree, its sum is zero
if( root == NULL ) {
return 0 ;
} else { // there is a tree
printf("element is = %d\n",root->data);
return root->data + sumNode( root->left ) + sumNode( root->right ) ;
}
}
int main() {
int arr[] = {1,2,3,4,5,6,7,8,9};
int i;
for(i=0;i<9;i++){
insert_Data(arr[i],head);
}
int result = sumNode(head);
printf("\n\n%d",result);
return 0;
}