Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 24, 2016 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/f4d6d81f300a0c7c26cc4bcdbe99b3db to your computer and use it in GitHub Desktop.
Save jianminchen/f4d6d81f300a0c7c26cc4bcdbe99b3db to your computer and use it in GitHub Desktop.
Leetcode 297 - Serialize and Deserialize a binary tree
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _297SerializeAndDeserializeTree
{
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
/*
* May 23, 2016
* Work on coding, source code from:
*
*/
class Program
{
static void Main(string[] args)
{
}
private static char delimiter = ',';
private static char emptyNode = '#';
// Encodes a tree to a single string.
public static String serialize(TreeNode root)
{
StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.ToString();
}
private static void serialize(TreeNode root, StringBuilder sb)
{
if (root == null)
{
sb.Append(emptyNode).Append(delimiter);
}
else
{
sb.Append(root.val).Append(delimiter);
serialize(root.left, sb);
serialize(root.right, sb);
}
}
// Decodes your encoded data to tree.
public TreeNode deserialize(string data)
{
LinkedList<string> nodes = new LinkedList<string>(data.Split(delimiter));
return deserialize(nodes);
}
private static TreeNode deserialize(LinkedList<string> nodes)
{
string nodeVal = nodes.First();
if (nodeVal.CompareTo(emptyNode.ToString()) == 0)
{
return null;
}
else
{
TreeNode node = new TreeNode(Int32.Parse(nodeVal));
node.left = deserialize(nodes);
node.right = deserialize(nodes);
return node;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment