zoukankan      html  css  js  c++  java
  • 606. Construct String from Binary Tree

    题目来源:

     https://leetcode.com/problems/construct-string-from-binary-tree/

    自我感觉难度/真实难度:hard/easy
     
    题意:

     把一个树,先序遍历一遍,左右孩子分别用括号包起来,不影响还原的情况下,删去多余的括号

    分析:
     
    自己的代码:
    class Solution(object):
        def tree2str(self, t):
            """
            :type t: TreeNode
            :rtype: str
            """
            pretree=self.preOrder(t)
            return str(pretree)
            
        def preOrder(self,root):
            if not root:
                return
            res=[]
            res.append(root.val)
            res.append('(')
            res.extend(self.preOrder(root.left))
            res.append(')')
            res.append('(')
            res.extend(self.preOrder(root.right))
            res.append(')')
            return res
    代码效率/结果:

    报错,运行不起来

     
    优秀代码:
    class Solution(object):
        def tree2str(self, t):
            """
            :type t: TreeNode
            :rtype: str
            """
            if not t:
                return ""
            res = ""
            left = self.tree2str(t.left)
            right = self.tree2str(t.right)
            if left or right:
                res += "(%s)" % left
            if right:
                res += "(%s)" % right
            return str(t.val) + res
    代码效率/结果:

    Runtime: 68 ms, faster than 34.47% of Python online submissions for Construct String from Binary Tree.

     
    最优化后的代码:
    class Solution(object):
        def tree2str(self, t):
            """
            :type t: TreeNode
            :rtype: str
            """
            if not t:
                return ''
            res = str(t.val)
            if t.left:
                res += '(' + self.tree2str(t.left) + ')'
                if t.right:
                    res += '(' + self.tree2str(t.right) + ')'
            elif t.right:
                res += '()' + '(' + self.tree2str(t.right) + ')'
            return res
     
    反思改进策略:

    1.对字符串的操作不灵敏      "hello"+"world"  

    2.如何定义一个字符串            str=""

  • 相关阅读:
    C++ 字符数组函数与string函数
    std::vector介绍
    DirectX开发环境配置
    基于序列图像的三维体绘的视线投射算法
    关于灰度图和彩色图
    cin函数的一点理解
    两个getline 输入带空格的字符串
    彩色图转灰度图的原理和参考源码
    牛顿迭代法求一个数的平方根
    约瑟夫环问题
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10211288.html
Copyright © 2011-2022 走看看