Skip to content

Instantly share code, notes, and snippets.

@lakshyaraj2006
Created September 24, 2025 15:45
Show Gist options
  • Select an option

  • Save lakshyaraj2006/035f58f88c32b5dc1646404dff69b8af to your computer and use it in GitHub Desktop.

Select an option

Save lakshyaraj2006/035f58f88c32b5dc1646404dff69b8af to your computer and use it in GitHub Desktop.
Convert 1D array to tree in C language.
#include<stdio.h>
#include<stdlib.h>
struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(char data) {
struct TreeNode* n = (struct TreeNode*)malloc(sizeof(struct TreeNode));
n->data = data;
n->left = NULL;
n->right = NULL;
}
void preOrder(struct TreeNode* root) {
if (root == NULL) return;
printf("%c ", root->data);
preOrder(root->left);
preOrder(root->right);
}
struct TreeNode* convertToTree(char* A, int n, int i) {
if (i >= n) return NULL;
struct TreeNode* root = createNode(A[i]);
root->left = convertToTree(A, n, 2*i + 1);
root->right = convertToTree(A, n, 2*i + 2);
return root;
}
int main(){
char A[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
int n = sizeof(A) / sizeof(A[0]);
struct TreeNode* root = convertToTree(A, n, 0);
preOrder(root);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment