首页 > 编程语言 > 详细

Python 解LeetCode:606 Construct String from Binary Tree

时间:2018-01-01 18:52:51      阅读:199      评论:0      收藏:0      [点我收藏+]
  • 题目描述:用先序遍历的方式把二叉树转换成字符串,其中结点用括号分割,具体示例见题目链接

  • 思路:
  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

Python 解LeetCode:606 Construct String from Binary Tree

原文:https://www.cnblogs.com/qiaojushuang/p/8167980.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!