各位如果看到博客内有广告,可以动手点一点,谢谢

MENU

LeetCode297. 二叉树的序列化与反序列化

August 9, 2018 • Read: 398 • LeetCode

题目链接:LeetCode297

题解

先序遍历、中序遍历、后序遍历进行序列化,然后同样的方式反序列化就行

代码
/**
 * 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 res = "";
    public String serialize(TreeNode root) {
        if(root == null)
            return "null,";
        String res = root.val + ",";
        res += serialize(root.left);
        res += serialize(root.right);
        return res;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] values = data.split(",");
        Queue<String> queue = new LinkedList<String>();
        for(int i = 0;i != values.length;i++)
            queue.offer(values[i]);
        return Back_Tree(queue);
    }
    public TreeNode Back_Tree(Queue<String> queue) {
        String value = queue.poll();
        if(value.equals("null"))
            return null;
        TreeNode head = new TreeNode(Integer.valueOf(value));
        head.left = Back_Tree(queue);
        head.right = Back_Tree(queue);
        return head;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
Archives Tip
QR Code for this page
Tipping QR Code