Answer to Question #242323 in C for Asjad

Question #242323
  1. . Construct a binary tree, where the input is given as an array. The node present at ’k’th index will have the pair of children at 2kth index and 2k+1th index in the array. Find the post order and pre order traversal for the constructed tree.
1
Expert's answer
2021-09-26T11:41:38-0400
#include <stdio.h>

size_t size = 13;
int64_t tree[] = {1, 4, -3, 5, 2, -4, -5, 3, 5, 2, 4, 0, 5};  // 13

inline size_t parent(size_t i) { return (i - 1) >> 1; }
inline size_t left(size_t i) { return (i << 1) + 1; }
inline size_t right(size_t i) { return (i << 1) + 2; }

void preOrderTreversal(size_t i) {
  if (i < size) {
    printf("%" PRId64 " ", tree[i]);
    preOrderTraversal(left(i));
    preOrderTraversal(right(i));
  }
}

void postOrderTraversal(size_t i) {
  if (i < size) {
    preOrderTraversal(left(i));
    preOrderTraversal(right(i));
    printf("%" PRId64 " ", tree[i]);
  }
}

void inOrderTraversal(size_t i) {
  if (i < size) {
    preOrderTraversal(left(i));
    printf("%" PRId64 " ", tree[i]);
    preOrderTraversal(right(i));
  }
}

int main() {
  preOrderTraversal(0);
  printf("\n");
  inOrderTraversal(0);
  printf("\n");
  postOrderTraversal(0);
  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS