A tree has a special property where leaves are represented with ‘L’ and non-leaf with ‘N’. Each node has either 0 or 2 children. If given preorder traversal of this tree, construct the tree.
Since every node has either 2 children or no child, we can surely say that if a node exists then its sibling also exists. So every time we are computing a subtree, we need to compute its sibling subtree as well.
Secondly, whenever we get ‘L’ in the input string, that is a leaf so we can stop for a particular subtree at that point. So after this ‘L’ node (left child of its parent ‘L’), it’s sibling starts. If ‘L’ node is right child of its parent, then we need to go up in the hierarchy to find next subtree to compute.
Also from http://stackoverflow.com/questions/4908545/construct-tree-with-pre-order-traversal-given
http://stackoverflow.com/questions/5890617/understanding-pseudocode-to-construct-tree-from-preorder-traversal/5890687#5890687
{
//Boundary Condition
if (A == NULL){
return NULL;
}
tree *node = newnode(A[*i]);
//On reaching leaf node, return
if (A[*i] == 'L'){
return node;
}
//Populate left sub tree
*i = *i + 1;
node->left = construct_tree(A, i);
//Populate right sub tree
*i = *i + 1;
node->right = construct_tree(A, i);
return node;
}
Read full article from Reconstruct tree from pre-order traversal | PROGRAMMING INTERVIEWS
Since every node has either 2 children or no child, we can surely say that if a node exists then its sibling also exists. So every time we are computing a subtree, we need to compute its sibling subtree as well.
Secondly, whenever we get ‘L’ in the input string, that is a leaf so we can stop for a particular subtree at that point. So after this ‘L’ node (left child of its parent ‘L’), it’s sibling starts. If ‘L’ node is right child of its parent, then we need to go up in the hierarchy to find next subtree to compute.
Also from http://stackoverflow.com/questions/4908545/construct-tree-with-pre-order-traversal-given
http://stackoverflow.com/questions/5890617/understanding-pseudocode-to-construct-tree-from-preorder-traversal/5890687#5890687
k = 0
input = ... get preorder traversal vector from user ...
Reconstruct(T)
if input[k] == N
T = new node with label N
k = k + 1
Reconstruct(T.left)
Reconstruct(T.right)
else
T = new node with label L
T.left = T.right = null
k = k + 1
tree* construct_tree(char* A, int *i){
//Boundary Condition
if (A == NULL){
return NULL;
}
tree *node = newnode(A[*i]);
//On reaching leaf node, return
if (A[*i] == 'L'){
return node;
}
//Populate left sub tree
*i = *i + 1;
node->left = construct_tree(A, i);
//Populate right sub tree
*i = *i + 1;
node->right = construct_tree(A, i);
return node;
}
Read full article from Reconstruct tree from pre-order traversal | PROGRAMMING INTERVIEWS