Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialize and Deserialize Binary Tree #287

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions Hard/SerializeandDeserializeBinaryTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {

// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root == null){
return "X";
}
String leftSerialized = serialize(root.left);
String rightSerialized = serialize(root.right);
return root.val + ","+leftSerialized + ","+rightSerialized;
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Queue<String> nodesLeft = new LinkedList<>();
nodesLeft.addAll(Arrays.asList(data.split(",")));
return deserializeHelper(nodesLeft);

}
public TreeNode deserializeHelper(Queue<String> nodesLeft){
String valueforNode = nodesLeft.poll();
if(valueforNode.equals("X")) return null;
TreeNode newNode = new TreeNode(Integer.valueOf(valueforNode));
newNode.left = deserializeHelper(nodesLeft);
newNode.right = deserializeHelper(nodesLeft);
return newNode;
}
}