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

  • 相关阅读:
    需求墙,挺有创意
    产品分析套路
    复杂问题的拆解分析,有点意思
    xss如何加载远程js的一些tips
    一次有趣的XSS漏洞挖掘分析(3)最终篇
    一次有趣的XSS漏洞挖掘分析(2)
    一次有趣的XSS漏洞挖掘分析(1)
    Java和WebSocket开发网页聊天室
    Socket.IO聊天室~简单实用
    C语言基于GTK+Libvlc实现的简易视频播放器(二)
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10211288.html
Copyright © 2011-2022 走看看