Leetcode 297. Serialize and Deserialize Binary Tree(递归)

Leetcode 297. Serialize and Deserialize Binary Tree

题目链接: Serialize and Deserialize Binary Tree

难度:Hard

题目大意:

给出二叉树,将二叉树转出String,再从String中构建出二叉树。

思路:

参考高赞回答,利用递归思想,对二叉树采用前序遍历,各个节点之间用“,”分隔存储到StringBuilder中去,null用“#”表示。从String中恢复二叉树的时候,根据分隔符得到所有二叉树节点的值,然后恢复出二叉树。

代码

/**
 * 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();
        return buildString(root,sb).toString();
    }
    private StringBuilder buildString(TreeNode root,StringBuilder s){
        if(root==null){
            return s.append("#").append(",");
        }
        else{//前序遍历
            s.append(root.val).append(",");
            buildString(root.left,s);
            buildString(root.right,s);
            return s;
        }
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        Queue<String> queue= new LinkedList<>(Arrays.asList(data.split(",")));
        TreeNode root=buildTree(queue);
        return root;
    }
    private TreeNode buildTree(Queue<String> queue){
        String val=queue.poll();
        if(val.equals("#")){
            return null;
        }
        else{
            TreeNode node=new TreeNode(Integer.parseInt(val));
            node.left=buildTree(queue);
            node.right=buildTree(queue);
            return node;
        }
    }
}

// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值