剑指-面试题37 序列化二叉树

序列化二叉树

题目
请实现两个函数,分别用来序列化和反序列化二叉树。

思路:

  • 序列化(题目要求按照层序遍历的顺序序列化,与剑指有所不同):
    (1)按照层次遍历的套路,设置辅助队列
    (2)空节点也要加入序列,所以每出队一个节点,判断是否为空
    – 空则加入“null”
    – 不空将其值加入序列中,然后左右子树入队(不管左右子树是否为空)

  • 反序列化
    (1)python:利用队列按层构建二叉树,每构建一个节点的左右子节点,指针向右移动1位。
    (2)C++:用一个vector辅助实现,先把序列存入vector,然后从根节点开始建树。每次i移动一个单位,j向右移动两次。


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) {
        ostringstream out;
        queue<TreeNode*> q;
        q.push(root);
                while (!q.empty()) {
            TreeNode* tmp = q.front();
            q.pop();
            if (tmp) {
                out<<tmp->val<<" ";
                q.push(tmp->left);
                q.push(tmp->right);
            } else {
                out<<"null ";
            }
        }
        return out.str();
    }
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream input(data);
        string val;
        vector<TreeNode*> vec;
        while(input >> val)
        {
            if(val=="null")
            {
                vec.push_back(NULL);
            }
            else
            {
                vec.push_back(new TreeNode(stoi(val)));
            }
        }
        int j=1;
        for(int i=0; j<vec.size(); ++i)
        {
        	//i一次走一步,j一次走两步
            if(vec[i]==NULL)
                continue;
            // 只要j没有到尾部
            if(j < vec.size())
                vec[i]->left = vec[j++];
            if(j < vec.size())
                vec[i]->right = vec[j++];
            
        }
        return vec[0];
    }
};

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

python

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

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        if not root:
            return "[]"
        queue = []
        queue.append(root)
        res = []
        while queue:
            temp = queue[0]
            queue.pop(0)
            if temp:
                res.append(str(temp.val))
                queue.append(temp.left)
                queue.append(temp.right)
            else:
                res.append("null")
        return '[' + ','.join(res) +']'
        

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        if data == "[]":
            return None
        vals = data[1:-1].split(',')
        i = 1
        root = TreeNode(int(vals[0]))
        queue = []
        queue.append(root)
        while queue: # 和C++中的for循环原理一样
            temp = queue[0]
            queue.pop(0)
            if vals[i] != "null":
                temp.left = TreeNode(int(vals[i]))
                queue.append(temp.left)
            i += 1
            if vals[i] != "null":
                temp.right = TreeNode(int(vals[i]))
                queue.append(temp.right)
            i += 1
        return root
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值