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=""

  • 相关阅读:
    SDL 学习及相关API
    ppm图像格式
    Gstreamer学习
    GObject对象系统
    Linux下查看文件和文件夹大小
    将输入的字符串按指定的长度进行拆分
    Ubuntu12.04 下安装Chrome浏览器
    Ubuntu12.04 下搭建Java开发环境
    Android 之 WebView
    Ubuntu Desktop 16.04 LTS 下成功配置Jupyter的两个python内核版本(2.7x,3.5x)
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10211288.html
Copyright © 2011-2022 走看看