You are currently viewing Easy Binary Tree Creation using Stack code

Easy Binary Tree Creation using Stack code

Binary Tree Creation using Stack code

This code is for Binary tree creation using stack. In this code first created node will be treated as root node. After that another function insert() will be called for adding the child nodes. Every time one node created and sent to stack for keeping track of that node.

For implementing Binary tree creation using stack, as name suggest stack is used for keeping track of the newly added nodes.

Other than Binary Tree creation using stack, we can also use queue for Binary Tree creation.

For Such more codes click here and for video tutorial click here.

				
					#include<stdio.h>

#include<stdlib.h>

typedef struct tree {
  int val;
  struct tree * lch;
  struct tree * rch;
}
tr;

typedef struct stack {
  tr * node;
  struct stack * next;
}
st;

void push(st ** , tr * );
tr * pop(st ** );
int isempty(st * );
tr * createroot();
void insert(st * );
void inorder(tr * );
void main() {
  st * h = NULL;
  tr * ptr;

  ptr = createroot();
  push( & h, ptr);
  insert(h);
  printf("\n\nInorder traversal form of the tree is : ");
  inorder(ptr);
}

tr * createroot() {
  int v;
  tr * ptr;
  printf("\nEnter the values : ");
  scanf("%d", & v);
  ptr = (tr * ) malloc(sizeof(tr));
  ptr -> val = v;
  ptr -> lch = ptr -> rch = NULL;
  return (ptr);
}

void insert(st * h) {
  tr * ptr, * temp;
  char ch;
  int v;
  while (!isempty(h)) {
    ptr = pop( & h);
    printf("\n%d has left child?(y/n) : ", ptr -> val);

    scanf(" %c", & ch);
    if (ch == 'y' || ch == 'Y') {
      printf("\nEnter the value : ");
      fflush(stdin);
      scanf("%d", & v);
      temp = (tr * ) malloc(sizeof(tr));
      temp -> val = v;
      temp -> lch = temp -> rch = NULL;
      ptr -> lch = temp;
      push( & h, temp);
    }
    printf("\n%d has right child?(y/n) : ", ptr -> val);
    scanf(" %c", & ch);
    if (ch == 'y' || ch == 'Y') {
      fflush(stdin);
      printf("\nEnter the value : ");
      scanf("%d", & v);
      temp = (tr * ) malloc(sizeof(tr));
      temp -> val = v;
      temp -> lch = temp -> rch = NULL;
      ptr -> rch = temp;
      push( & h, temp);
    }
  }
}

void push(st ** h, tr * ptr) {
  st * temp;
  temp = (st * ) malloc(sizeof(st));
  temp -> node = ptr;
  temp -> next = * h;
  * h = temp;
}

tr * pop(st ** h) {
  tr * ptr;
  ptr = ( * h) -> node;
  * h = ( * h) -> next;
  return ptr;
}

int isempty(st * h) {
  if (h == NULL)
    return 1;
  else
    return 0;
}

void inorder(tr * h) {
  if (h != NULL) {
    inorder(h -> lch);
    printf("%d,", h -> val);
    inorder(h -> rch);
  }
}
				
			

Leave a Reply