TreeNode root
in the method serializeTree
. This method should serialize the binary tree and output a String str, which is then used as an input parameter for the method restoreTree
. restoreTree
should create a Binary Tree that is structurally identical to the one you serialized and return the root node of the tree. Your task is to fill in the logic for these 2 methods. Don't worry about passing the serialized String to restoreTree
- that will be done automatically when you run your code. Feel free to use any notation you prefer when serializing the binary tree. The choice of traversal algorithm is also open - but try and limit the time complexity of both methods to O(n).restoreTree
that you use to serialize in serializeTree
.Example:
1
/ \
2 3
Serialization :
Output => "1,2,3"
Restoring Tree from "1,2,3" :
Output ->
1
/ \
2 3
serializeTree
is a simple tree traversal problem. The key there is to use a helper method that gets passed in a StringBuilder
and recursively builds the String with a pre-order traversal. Be sure to account for null
nodes and add them to the String. restoreTree
should tokenize the String into a list of Strings
- nodesSplit = str.split(",")
and pass this list to a helper method. The helper method can recursively remove elements from the head of this list as it performs a pre-order traversal to re-create the binary tree.
public String serializeTree(TreeNode root){ } public TreeNode restoreTree(String str){ }
C
Java
Python