449. Serialize and Deserialize BST
Last updated
Last updated
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}/**
* Time complexity :
* Space complexity :
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null) return null;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
if(node != null) {
sb.append(node.val).append(",");
stack.push(node.right);
stack.push(node.left);
} else {
sb.append("#,");
}
}
return sb.substring(0, sb.length()-1);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data == null) return null;
return helper(data.split(","), new int[]{0});
}
private TreeNode helper(String[] values, int[] index) {
if("#".equals(values[index[0]])) return null;
TreeNode node = new TreeNode(Integer.parseInt(values[index[0]]));
index[0] += 1;
node.left = helper(values, index);
index[0] += 1;
node.right = helper(values, index);
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// String tree = ser.serialize(root);
// TreeNode ans = deser.deserialize(tree);
// return ans;/**
* Time complexity :
* Space complexity :
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null) return null;
StringBuilder sb = new StringBuilder();
serialize(root, sb);
return sb.substring(0, sb.length()-1);
}
private void serialize(TreeNode node, StringBuilder sb) {
if(node == null) {
sb.append("#,");
return;
}
sb.append(node.val).append(",");
serialize(node.left, sb);
serialize(node.right, sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data == null) return null;
return helper(data.split(","), new int[]{0});
}
private TreeNode helper(String[] values, int[] index) {
if("#".equals(values[index[0]])) return null;
TreeNode node = new TreeNode(Integer.parseInt(values[index[0]]));
index[0] += 1;
node.left = helper(values, index);
index[0] += 1;
node.right = helper(values, index);
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// String tree = ser.serialize(root);
// TreeNode ans = deser.deserialize(tree);
// return ans;