Leetcode 449. 序列化和反序列化二叉搜索树(包括序列化反序列过程以及仅由前序遍历递归构造二叉树搜索树两个过程)

 

对于一般的二叉树,我们对其进行序列化和反序列化,可以在前序遍历的基础上通过将其所有节点,包括空结点输出的方式保存下来。由于二叉搜索树定义,只需要其前序遍历,就可以还原整个二叉树。还原的时候由两种方法,一种是排序构造中序遍历,通过中序遍历和前序遍历还原二叉树。还有一种是维护一个范围,在前序遍历的基础上,递归的完成构建。这里选择方案二。

 

其中解析字符串的过程使用sstream,不必在这里手动实现解析。

/**
 * 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:

    void dfs(TreeNode* root, string& s){
        if(root == nullptr){
            return;
        }
        s += to_string(root->val) + " ";
        dfs(root->left, s);
        dfs(root->right, s);
    }

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string s;
        dfs(root, s);
        return s;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        vector<int> preorder;
        stringstream ssin(data);
        int x = 0;
        while(ssin >> x){
            preorder.push_back(x);
        }
        int u = 0;

        return helper(preorder, u, INT_MIN, INT_MAX);
    }

    TreeNode* helper(vector<int>& preorder, int& u, int min, int max){
        if(u >= preorder.size() || preorder[u] > max || preorder[u] < min){
            return nullptr;
        }
        auto root = new TreeNode(preorder[u++]);
        root->left = helper(preorder, u, min, root->val);
        root->right = helper(preorder, u, root->val, max);
        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;

优雅的Python实现:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root: TreeNode) -> str:
        """Encodes a tree to a single string.
        """
        def postorder(root):
            return [root.val] + postorder(root.left) + postorder(root.right) if root != None else []
        
        return " ".join(map(str, postorder(root)))
        

    def deserialize(self, data: str) -> TreeNode:
        """Decodes your encoded data to tree.
        """
        def helper(lower = float('-inf'), upper = float('inf')):
            if not data or data[0] < lower or data[0] > upper:
                return None
            val = data.pop(0)
            root = TreeNode(val)
            root.left = helper(lower, val)
            root.right = helper(val, upper)
            return root
        data = list(map(int, data.split()))
        return helper()

# Your Codec object will be instantiated and called as such:
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值