Python 解LeetCode:606 Construct String from Binary Tree

  • 题目描述:用先序遍历的方式把二叉树转换成字符串,其中结点用括号分割,具体示例见题目链接

  • 思路:

  1. 先序遍历,先把根结点的值转化成字符串,然后递归的把左右子树的值转化成字符串
  2. 把1中的根结点和左右子结点的字符串连接起来就是结果,其中需要注意:
    • 如果右子树存在值,左子树无论有没有值,都需要用()括起来
    • 如果右子树不存在值,左子树只有在存在值的时候才括起来
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def tree2str(self, t):
        """
        :type t: TreeNode
        :rtype: str
        """
        if not t:
            return ''
        root = str(t.val)
        left = self.tree2str(t.left)
        right = self.tree2str(t.right)
        if right:
            return root + '(' + left + ')(' + right + ')'
        else:
            if left:
                return root + '(' + left + ')'
            else:
                return root
原文地址:https://www.cnblogs.com/qiaojushuang/p/8167980.html