c - Simple inorder tree traversal giving a non terminating loop. (using arrays) -


following code building simple tree. approach i'm using here if particular node @ index n in arr[] array, has it's left child @ index 2*n+1 , right child @ 2*n+2 in same arr[] array. , i'm doing inorder traversal. however, i'm getting infinite loop @ node d output. love if me out here.

#include <stdio.h> #include <malloc.h>  struct node {    struct node * lc;    char data;    struct node * rc; };  char arr[] = {'a','b','c','d','e','f','g','\0','\0','h','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0'}; struct node * root = null;  struct node * buildtree(int rootindex) {     struct node * temp = null;      if(arr[rootindex]!='\0')     {             temp = (struct node *)malloc(sizeof(struct node));             temp->lc = buildtree(rootindex * 2 + 1);             temp->data = arr[rootindex];             temp->rc = buildtree(rootindex * 2 + 2);     }      return temp; }  void inorder(struct node * parent) {     while(parent != null)     {         inorder(parent->lc);         printf("%c\t",parent->data);         inorder(parent->rc);     } }  int main() {     root = buildtree(0);     inorder(root);     return 0; } 

like bluepixy mentioned in comments, need replace while in inorder() method if. when building tree, d forms left-most child. therefore during in-order traversal, d encountered first node printed. while loop keeps printing condition never becomes false.

i'm sure tool gdb have done better job in explaining this.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -