Created
May 21, 2013 15:59
-
-
Save bittib/5620951 to your computer and use it in GitHub Desktop.
Serialize and Deserialize a Binary Tree (pre order).
This file contains 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 TreeNode{ | |
int val; | |
TreeNode left, right; | |
TreeNode(int val){ | |
this.val = val; | |
} | |
} | |
public String serialize(TreeNode root){ | |
StringBuilder sb = new StringBuilder(); | |
serialize(root, sb); | |
return sb.toString(); | |
} | |
private void serialize(TreeNode x, StringBuilder sb){ | |
if (x == null) { | |
sb.append("# "); | |
} else { | |
sb.append(x.val + " "); | |
serialzie(x.left, sb); | |
serialzie(x.right, sb); | |
} | |
} | |
public TreeNode deserialize(String s){ | |
if (s == null || s.length() == 0) return null; | |
StringTokenizer st = new StringTokenizer(s, " "); | |
return deserialize(st); | |
} | |
private TreeNode deserialize(StringTokenizer st){ | |
if (!st.hasMoreTokens()) | |
return null; | |
String val = st.nextToken(); | |
if (val.equals("#")) | |
return null; | |
TreeNode root = new TreeNode(Integer.parseInt(val)); | |
root.left = deserialize(st); | |
root.right = deserialize(st); | |
return root; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment