Created
June 3, 2020 11:16
-
-
Save m-khooryani/87417965766c308b015662f7c8751709 to your computer and use it in GitHub Desktop.
De/Serialize Binary Tree
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
This problem was asked by Google. | |
Given the root to a binary tree, implement serialize(root), | |
which serializes the tree into a string, and deserialize(s), | |
which deserializes the string back into the tree. | |
For example, given the following Node class | |
class Node: | |
def __init__(self, val, left=None, right=None): | |
self.val = val | |
self.left = left | |
self.right = right | |
The following test should pass: | |
node = Node('root', Node('left', Node('left.left')), Node('right')) | |
assert deserialize(serialize(node)).left.left.val == 'left.left' |
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
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Node node = new Node("root", new Node("left", new Node("left.left"), null), new Node("right")); | |
string serializedNode = node.Serialize(); | |
var deserializedNode = Node.Deserialize(serializedNode); | |
if (deserializedNode.Left.Left.Val != "left.left") | |
{ | |
throw new Exception("incorrect!"); | |
} | |
} | |
} | |
class Node | |
{ | |
private const string Nil = "null"; | |
public string Val { get; private set; } | |
public Node Left { get; private set; } | |
public Node Right { get; private set; } | |
public Node(string val) | |
: this(val, null, null) | |
{ | |
} | |
public Node(string val, Node left, Node right) | |
{ | |
if (string.IsNullOrWhiteSpace(val) || val.Contains(" ") || val == Nil) | |
{ | |
throw new ArgumentException(nameof(val)); | |
} | |
this.Val = val; | |
this.Left = left; | |
this.Right = right; | |
} | |
public string Serialize() | |
{ | |
if (string.IsNullOrWhiteSpace(this.Val)) | |
{ | |
return Nil; | |
} | |
return $"{this.Val} {this.Left?.Serialize() ?? Nil} {this.Right?.Serialize() ?? Nil}"; | |
} | |
public static Node Deserialize(string serialized) | |
{ | |
var splitted = serialized.Split(' '); | |
var queue = new Queue<string>(splitted); | |
return Node.Deserialize(queue); | |
} | |
private static Node Deserialize(Queue<string> q) | |
{ | |
if (q.Count == 0) | |
{ | |
return null; | |
} | |
var val = q.Dequeue(); | |
if (string.IsNullOrWhiteSpace(val) || val == Nil) | |
{ | |
return null; | |
} | |
return new Node(val, Deserialize(q), Deserialize(q)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment