LeetCode 题解(280) :Serialize and Deserialize Binary Tree

本文详细阐述了如何通过一种特定的序列化方法将二叉树转换为字符串,反之亦能将字符串反序列化为原始树结构。通过深度优先搜索遍历树节点,使用队列辅助实现序列化与反序列化过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

    1
   / \
  2   3
     / \
    4   5
as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

题解:

就用了这种"[1,2,3,null,null,4,5]"序列化方法,因为实现起来比较容易,其它方法想必也大同小异。本质就是树的遍历。

C++版:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        if(root == NULL)
            return "";
        string serialized = "";
        int h = 0, level = 0;
        treeHeight(root, h, level);
        
        queue<pair<TreeNode*, int>> q;
        q.push(pair<TreeNode*, int>(root, 1));
        serialized += to_string(root->val) + " ";
        while(!q.empty()) {
            auto cur = q.front();
            q.pop();
            if(cur.first->left != NULL) {
                serialized += to_string(cur.first->left->val) + " ";
                q.push(pair<TreeNode*, int>(cur.first->left, cur.second + 1));
            } else {
                if(cur.second < h)
                    serialized += "NULL ";
            }
            if(cur.first->right != NULL) {
                serialized += to_string(cur.first->right->val) + " ";
                q.push(pair<TreeNode*, int>(cur.first->right, cur.second + 1));
            } else {
                if(cur.second < h)
                    serialized += "NULL ";
            }
        }

        return serialized;
    }
    
    void treeHeight(TreeNode* root, int& h, int cur) {
        if(root == NULL)
            return;
        cur++;
        if(h < cur)
            h = cur;
        treeHeight(root->left, h, cur);
        treeHeight(root->right, h, cur);
    }


    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if(data.length() == 0)
            return NULL;
        vector<string> nodes;
        int i = 0, last = 0;
        while(data.find(" ", i) != string::npos) {
            i = data.find(" ", i) + 1;
            nodes.push_back(data.substr(last, i - last - 1));
            last = i;
        }

        TreeNode* root = new TreeNode(stoi(nodes[0]));
        queue<TreeNode*> q;
        q.push(root);
        i = 1;
        while(i < nodes.size() && !q.empty()) {
            TreeNode* cur = q.front();
            q.pop();
            if(i < nodes.size() && nodes[i] != "NULL") {
                TreeNode* newNode = new TreeNode(stoi(nodes[i]));
                cur->left = newNode;
                q.push(newNode);
            }
            i++;
            if(i < nodes.size() && nodes[i] != "NULL") {
                TreeNode* newNode = new TreeNode(stoi(nodes[i]));
                cur->right = newNode;
                q.push(newNode);
            }
            i++;
        }
        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

Java版:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Pair {
    TreeNode node;
    int level;
    Pair(TreeNode n, int l) {node = n; level = l;}
}

class intWrapper {
    int val;
    intWrapper(int v) {val = v;}
}
 
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null)
            return "";
        StringBuilder serialized = new StringBuilder();
        intWrapper h = new intWrapper(0);
        int level = 0;
        treeHeight(root, h, level);
        System.out.println(h.val);
        Queue<Pair> q = new LinkedList<Pair>();
        serialized.append(Integer.toString(root.val));
        serialized.append(" ");
        q.add(new Pair(root, 1));
        while(!q.isEmpty()) {
            Pair cur = q.poll();
            if(cur.node.left != null) {
                serialized.append(cur.node.left.val);
                serialized.append(" ");
                q.add(new Pair(cur.node.left, cur.level + 1));
            } else {
                if(cur.level < h.val)
                    serialized.append("null ");
            }
            if(cur.node.right != null) {
                serialized.append(cur.node.right.val);
                serialized.append(" ");
                q.add(new Pair(cur.node.right, cur.level + 1));
            } else {
                if(cur.level < h.val)
                    serialized.append("null ");
            }
        }
        System.out.println(serialized.toString());
        return serialized.toString();
    }
    
    void treeHeight(TreeNode root, intWrapper h, int cur) {
        if(root == null)
            return;
        cur++;
        if(h.val < cur)
            h.val = cur;
        treeHeight(root.left, h, cur);
        treeHeight(root.right, h, cur);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.length() == 0)
            return null;
        String[] nodes = data.split("\\s");
        TreeNode root = new TreeNode(Integer.parseInt(nodes[0]));
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        int i = 1;
        while(i < nodes.length && !q.isEmpty()) {
            TreeNode cur = q.poll();
            if(i < nodes.length && !nodes[i].equals("null")) {
                TreeNode newNode = new TreeNode(Integer.parseInt(nodes[i]));
                cur.left = newNode;
                q.add(newNode);
            }
            i++;
            if(i < nodes.length && !nodes[i].equals("null")) {
                TreeNode newNode = new TreeNode(Integer.parseInt(nodes[i]));
                cur.right = newNode;
                q.add(newNode);
            }
            i++;
        }
        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值