首页 > 试题广场 >

二叉树的序列化

[编程题]二叉树的序列化
  • 热度指数:8682 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

二叉树被记录成文件的过程叫做二叉树的序列化。序列化的方法有很多,这里我们采用括号序列的方法将其序列化,所谓括号序列指的是对于一个节点生成一个括号,括号内是其子树的括号序列,其中左儿子(若存在)的括号在前,右儿子(若存在)的括号在后。对于给定的树,请设计高效的算法,将其序列化。

给定一个树的根节点指针root,请返回一个字符串,代表其序列化后的括号序列。


说明:本题目包含复杂数据结构TreeNode,点此查看相关信息

格式化输出

class TreeToSequence:
    def toSequence(self, root):
        if root:
            return "(%s%s)" % (self.toSequence(root.left),self.toSequence(root.right))
        else:
            return ""
编辑于 2018-10-14 22:46:33 回复(0)
class TreeToSequence:
    def toSequence(self, root):
        if not root:#该树为空,则返回的字符串也为空
            return ''
        left,right=root.left,root.right
        if left==None and right==None:#左右子树皆为空,则只有该数本身的括号
            return '()'
        else:
            return '('+self.toSequence(left)+self.toSequence(right)+')'

发表于 2018-08-19 15:10:34 回复(0)

python solution

class TreeToSequence:
    def toSequence(self, root):
        if not root: return ""
        res = "("
        res += self.toSequence(root.left)
        res += self.toSequence(root.right)
        res += ")"
        return res
发表于 2017-11-07 18:17:29 回复(0)

问题信息

难度:
3条回答 17863浏览

热门推荐

通过挑战的用户

查看代码