Solution:
import java.util.LinkedList; public class SerializeDeserializeTree { public static void main(String[] args) { String tree = "1,1,2,3,1,2,3,1,#,#,#,#,3"; TreeNode root = deserialize(tree); System.out.print("serializeTree: "+serializeTree(root)); } public static class TreeNode { int val; TreeNode[] child; TreeNode(int x) { this.val = x; this.child = new TreeNode[3]; } } public static int getDepth(TreeNode root) { if(root == null) { return 0; } return Math.max(Math.max(getDepth(root.child[0]), getDepth(root.child[1])), getDepth(root.child[2])) + 1; }
//serialize public static String serializeTree(TreeNode root) { if(root == null) { return "#"; } StringBuilder res = new StringBuilder(); LinkedListqueue = new LinkedList (); int depth = getDepth(root); queue.add(root); res.append(root.val).append(","); int last = 1; int cur = 0; int level = 1; while(!queue.isEmpty()) { TreeNode node = queue.poll(); last--; if(node.child[0] != null) { res.append(node.child[0].val).append(","); queue.add(node.child[0]); cur++; }else if(level < depth){ res.append("#").append(","); } if(node.child[1] != null) { res.append(node.child[1].val).append(","); queue.add(node.child[1]); cur++; }else if(level < depth){ res.append("#").append(","); } if(node.child[2] != null) { res.append(node.child[2].val).append(","); queue.add(node.child[2]); cur++; }else if(level < depth){ res.append("#").append(","); } if(last == 0 && !queue.isEmpty()) { last = cur; cur = 0; level++; } } res = res.deleteCharAt(res.length() - 1); return res.toString(); } //deserialize public static TreeNode deserialize(String tree) { if (tree == null || tree.length() == 0) return null; String[] nodes = tree.split(","); if (nodes[0] == "#") return null; TreeNode root = new TreeNode(Integer.parseInt(nodes[0])); LinkedList queue = new LinkedList (); queue.add(root); for (int i = 1; i < nodes.length; i = i + 3) { TreeNode r = queue.poll(); if (!nodes[i].equals("#")) { TreeNode n = new TreeNode(Integer.parseInt(nodes[i])); queue.add(n); r.child[0] = n; } if (!nodes[i + 1].equals("#")) { TreeNode n = new TreeNode(Integer.parseInt(nodes[i + 1])); queue.add(n); r.child[1] = n; } if(!nodes[i + 2].equals("#")) { TreeNode n = new TreeNode(Integer.parseInt(nodes[i + 2])); queue.add(n); r.child[2] = n; } } return root; } }
No comments:
Post a Comment