Leetcode 449. Serialize and Deserialize BST(递归)

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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值