LeetCode---606. Construct String from Binary Tree

题目

你需要通过前序遍历一个二叉树,构造出一个由数字和括号组成的字符串。null节点有空括号来表示“()”。你需要忽略所有的空括号对如果它不影响字符串和原始二叉树的对应关系。如下例子所示:
例子一:
Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4

Output: “1(2(4))(3)”

例子二:
Input: Binary tree: [1,2,3,null,4]
1
/ \
2 3
\
4

Output: “1(2()(4))(3)”

Python题解

class Solution(object):
    def tree2str(self, t):
        """
        :type t: TreeNode
        :rtype: str
        """
        if t is None:
            return ""
        if t.left is None and t.right is None:
            return str(t.val)
        if t.right is None:
            return str(t.val) + "(" + self.tree2str(t.left) + ")"
        return str(t.val) + "(" + self.tree2str(t.left) + ")(" + \
               self.tree2str(t.right) + ")"

猜你喜欢

转载自blog.csdn.net/leel0330/article/details/80215716