Leetcode 449. Serialize and Deserialize BST
题目链接: 449. Serialize and Deserialize BST
难度:Medium
题目大意:
给出二叉搜索树,将其转成String,再从String中构建出二叉搜索树。本题与 Leetcode 297. Serialize and Deserialize Binary Tree类似。
思路:
参考高赞回答,利用递归思想,对二叉搜索树采用前序遍历,各个节点之间用“,”分隔存储到StringBuilder中去。从String中恢复二叉搜索树的时候,根据分隔符得到所有二叉搜索树节点的值,根据二叉搜索树的特点可以知道某个节点是否为null,然后恢复出二叉搜索树。
代码
/**
* 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) {
StringBuilder sb=new StringBuilder();
buildString(root,sb);
return sb.toString();
}
public void buildString(TreeNode root,StringBuilder sb){
if(root==null){
return;
}
sb.append(root.val).append(",");
buildString(root.left,sb);
buildString(root.right,sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data.isEmpty()){
return null;
}
Queue<String> queue=new LinkedList<>(Arrays.asList(data.split(",")));
return buildTree(queue,Integer.MIN_VALUE,Integer.MAX_VALUE);
}
public TreeNode buildTree(Queue<String> queue,int low,int high){
if(queue.isEmpty()){
return null;
}
int val=Integer.parseInt(queue.peek());
if(val<low||val>high){
return null;
}
queue.poll();
TreeNode root=new TreeNode(val);
root.left=buildTree(queue,low,val);
root.right=buildTree(queue,val,high);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// String tree = ser.serialize(root);
// TreeNode ans = deser.deserialize(tree);
// return ans;