Created
September 7, 2017 00:55
-
-
Save umbs/4f48c0655225923ba56594314cab6447 to your computer and use it in GitHub Desktop.
This file contains 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
typedef struct node_ { | |
int key; | |
struct node_ *left, *right, *parent; | |
} node; | |
// A utility function to create a new node | |
node *newNode(int item) { | |
node *temp = (node *)malloc(sizeof(node)); | |
temp->key = item; | |
temp->left = temp->right = temp->parent = NULL; | |
return temp; | |
} | |
/* pre-order traversal. -1 indicates NULL node. Assumption is that a node with -1 key doesn't exist | |
* Serialized tree is saved in array, passed as argument */ | |
void serialize(node *root, int *arr, int *sz) { | |
static int idx; | |
if(root==NULL) { arr[idx++] = -1; return; } | |
arr[idx++] = root->key; | |
serialize(root->left, arr, sz); | |
serialize(root->right, arr, sz); | |
*sz = idx; // caller will know the last index of array | |
} | |
/* Input is pre-order printed array. Return a Binary Tree | |
* NOTE: this implementation does not require to know the size of the array. It assumes are array is well formed through serialization. | |
*/ | |
node *deserialize(int *arr) { | |
static int idx; | |
if(arr[idx] == -1) { idx++; return NULL; } | |
node *n = newNode(arr[idx++]); | |
n->left = deserialize(arr); | |
n->right = deserialize(arr); | |
return n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment