【Leetcode】606. Construct String from Binary Tree 解题报告

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dpengwang/article/details/88204870

在这里插入图片描述
将二叉树以 root(left_child)(right_child)的形式构建成字符串,省去不需要的括号(右子树为None的时候可以不用)

方法1 递归法

当节点为叶子节点时,直接返回值不需要加括号,如果左子树为None右子树不为None,那么左子树的空字符串也要用括号括起来,如果左子树不为None右子树为None,则右子树的空字符串可以省略


class Solution1:
    def tree2str(self, root):
        """
        :type t: TreeNode
        :rtype: str
        """
        if root == None:
            return ""
        if root.left == None and root.right == None:
            return "%s" % (str(root.val))
        else:
            if root.left == None:
                return "%s()(%s)" % (str(root.val),self.tree2str(root.right))
            elif root.right == None:
                return "%s(%s)" % (str(root.val), self.tree2str(root.left))
            else:
                return "%s(%s)(%s)" % (str(root.val), self.tree2str(root.left), self.tree2str(root.right)

改进后的递归

class Solution1:
    def tree2str(self, root):
        """
        :type t: TreeNode
        :rtype: str
        """
        res = ""
        if root:
            res += str(root.val)
            if root.left or root.right:
                res += "(%s)" % (self.tree2str(root.left))
            if root.right:
                res += "(%s)" % (self.tree2str(root.right))
        return res

方法2 非递归

后续遍历二叉树,将子树构成的字符串保存在dict中,回溯到父节点时从dict中查找即可

class Solution2:
    def tree2str(self, root):
        """
        :type t: TreeNode
        :rtype: str
        """
        if root == None:
            return ""
        stack, pNode, prev, res = [], root, None, ""
        from collections import  defaultdict
        dictionary = defaultdict(str)
        while(len(stack) or pNode):
            if pNode:
                stack.append(pNode)
                pNode = pNode.left
            else:
                pNode = stack[-1]
                if pNode.right == None or pNode.right == prev:
                    if pNode.left == None and pNode.right == None:
                        dictionary[pNode] = str(pNode.val)
                    else:
                        if pNode.right == None:
                                dictionary[pNode] = "%s(%s)" % (str(pNode.val),dictionary[pNode.left])
                        else:
                            dictionary[pNode] = "%s(%s)(%s)" % (str(pNode.val),dictionary[pNode.left], dictionary[pNode.right])

                    prev  = pNode
                    pNode = None
                    stack.pop()
                else:
                    pNode = pNode.right
        return dictionary[root]


猜你喜欢

转载自blog.csdn.net/dpengwang/article/details/88204870