思路:
回溯
代码:
代码语言:javascript复制 String Serialize(TreeNode root) {
if (root==null){
return "#!";
}
//先序遍历
String res=root.val "!";
res =Serialize(root.left);
res =Serialize(root.right);
return res;
}
TreeNode Deserialize(String str) {
if (str==null){
return null;
}
String[] nodes=str.split("!");
Queue<String> queue= new LinkedList<>();
for (String node : nodes) {
queue.offer(node);
}
return reBuildTree(queue);
}
private TreeNode reBuildTree(Queue<String> queue) {
String poll = queue.poll();
if ("#".equals(poll)){
return null;
}
TreeNode currNode=new TreeNode(Integer.parseInt(poll));
currNode.left=reBuildTree(queue);
currNode.right=reBuildTree(queue);
return currNode;
}