Last active
June 19, 2019 16:31
-
-
Save sogwiz/f1138407067383712d06022b0c2669b3 to your computer and use it in GitHub Desktop.
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
public class SerializeDeserializeBinaryTree { | |
public static void main(String args[]){ | |
TreeNode root = new TreeNode(3); | |
root.left = new TreeNode(5); | |
root.left.left = new TreeNode(6); | |
root.left.right = new TreeNode(2); | |
root.left.right.left = new TreeNode(7); | |
root.left.right.right = new TreeNode(4); | |
root.right = new TreeNode(1); | |
root.right.left = new TreeNode(0); | |
root.right.right = new TreeNode(8); | |
String out = serializeIterative(root); | |
//remove the final comma from the string so that we can split this str into a list eventually | |
out = out.substring(0, out.length()-1); | |
TreeNode deserialTree = deSerializeIterative(out); | |
System.out.println("hi"); | |
} | |
public static String serializeIterative(TreeNode root) { | |
Queue<TreeNode> q = new LinkedList<>(); | |
StringBuilder sb = new StringBuilder(); | |
q.add(root); | |
while(!q.isEmpty()){ | |
TreeNode n = q.poll(); | |
if(n==null){ | |
//use the "#" character as the sentinel | |
sb.append("#,"); | |
}else{ | |
sb.append(n.val + ","); | |
q.add(n.left); | |
q.add(n.right); | |
} | |
} | |
return sb.toString(); | |
} | |
public static TreeNode deSerializeIterative(String data) { | |
List<String> list = new ArrayList<>(Arrays.asList(data.split(","))); | |
TreeNode root = new TreeNode(Integer.valueOf(list.get(0))); | |
Queue<TreeNode> q = new LinkedList<>(); | |
q.add(root); | |
int index = 1; | |
while(!q.isEmpty() && index < list.size()){ | |
TreeNode curr = q.poll(); | |
if(!list.get(index).equals("#")){ | |
curr.left = new TreeNode(Integer.valueOf(list.get(index))); | |
q.add(curr.left); | |
} | |
index++; | |
if(!list.get(index).equals("#")){ | |
curr.right = new TreeNode(Integer.valueOf(list.get(index))); | |
q.add(curr.right); | |
} | |
index++; | |
} | |
return root; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment