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

原文地址:https://www.cnblogs.com/captain-dl/p/10211288.html