Created
September 24, 2025 16:03
-
-
Save lakshyaraj2006/b1b7a60dc73b7ccd87928481c01a112d to your computer and use it in GitHub Desktop.
Convert tree to 1D array in C language.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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; | |
| } | |
| int countNodes(struct TreeNode* root) { | |
| if (root == NULL) return 0; | |
| return 1 + countNodes(root->left) + countNodes(root->right); | |
| } | |
| void convertToArray(struct TreeNode* root, char* A, int i, int n) { | |
| if (root == NULL || i >= n) return; | |
| A[i] = root->data; | |
| convertToArray(root->left, A, 2*i + 1, n); | |
| convertToArray(root->right, A, 2*i + 2, n); | |
| } | |
| int main(){ | |
| struct TreeNode* root = createNode('A'); | |
| struct TreeNode* node1 = createNode('B'); | |
| struct TreeNode* node2 = createNode('C'); | |
| struct TreeNode* node3 = createNode('D'); | |
| struct TreeNode* node4 = createNode('E'); | |
| struct TreeNode* node5 = createNode('F'); | |
| struct TreeNode* node6 = createNode('G'); | |
| root->left = node1; | |
| root->right = node2; | |
| node1->left = node3; | |
| node1->right = node4; | |
| node2->left = node5; | |
| node2->right = node6; | |
| int n = countNodes(root); | |
| char* A = malloc(n * sizeof(char)); | |
| convertToArray(root, A, 0, n); | |
| for (int i = 0; i < n; i++) | |
| { | |
| printf("%c ", A[i]); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment