Skip to content

Instantly share code, notes, and snippets.

@sdpatil
Created August 12, 2017 19:42
Show Gist options
  • Save sdpatil/118c2bb4df1e76edf0de26e76cb2ae23 to your computer and use it in GitHub Desktop.
Save sdpatil/118c2bb4df1e76edf0de26e76cb2ae23 to your computer and use it in GitHub Desktop.
Reconstruct a binary tree from preorder traversal with mark
import java.util.List;
/*
Problem: Given pre order traversal data of a binary tree where null markers are used when a node is empty
construct binary tree
{"H","B","F",null,null,"E","A",null,null,null,"C",null,"D",null,"G","I",null,null,null}
H
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
B C
/ \ \
/ \ \
/ \ \
/ \ \
F E D
/ \
/ \
A G
/
I
Solution: In preorder traversal first comes root then left tree followed by its left tree until we hit null
then right child. we can use this to make recursive calls like this
*/
public class ConstructFromPreOrderTraversal {
private Integer subtreeIdx;
public BinaryTreeNode<String> reconstructPreorder(List<String> preOrder) {
subtreeIdx = 0;
return reconstructPreorderHelper(preOrder);
}
public BinaryTreeNode<String> reconstructPreorderHelper(List<String> preOrder) {
String subTreeKey = preOrder.get(subtreeIdx);
subtreeIdx++;
//Found null marker so return
if(subTreeKey == null)
return null;
// Create left child
BinaryTreeNode leftChild = reconstructPreorderHelper(preOrder);
//Create right child
BinaryTreeNode rightChild = reconstructPreorderHelper(preOrder);
return new BinaryTreeNode<String>(subTreeKey,leftChild,rightChild);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment