Problem Statement
Pattern: Related: 652. Find Duplicate Subtrees
Solution
// preorder build string fun
void preString(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append("#").append(" ");
return;
}
sb.append(root.val).append(" ");
preString(root.left, sb);
preString(root.right, sb);
}
// preorder build nodes fun
TreeNode preNode(Queue<String> nodes) {
String val = nodes.remove();
if (val.equals("#")) return null;
TreeNode root = new TreeNode(Integer.parseInt(val));
root.left = preNode(nodes);
root.right = preNode(nodes);
return root;
}
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
preString(root, sb);
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String str) {
Queue<String> nodes = new LinkedList<>(Arrays.asList(str.split(" ")));
return preNode(nodes);
}
Notes
- preorder traverse, build string
- preorder traverse, build tree 🤷