【LeetCode】606. Construct String from Binary Tree 解题报告(Python)

本文介绍了一道LeetCode题目,即如何将二叉树转换为字符串形式,并遵循特定的省略规则。文章提供了详细的解题思路,采用先序遍历的方法,并附带了Python代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/construct-string-from-binary-tree/description/

题目描述

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair “()”. And you need to omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.

Example 1:

Input: Binary tree: [1,2,3,4]
       1
     /   \
    2     3
   /    
  4     

Output: "1(2(4))(3)"

Explanation: Originallay it needs to be "1(2(4)())(3()())", 
but you need to omit all the unnecessary empty parenthesis pairs. 
And it will be "1(2(4))(3)".

Example 2:

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

Output: "1(2()(4))(3)"

Explanation: Almost the same as the first example, 
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

题目大意

把二叉树转换成字符串,形式是节点值(左子树形式)(右子树形式),其中左子树形式和右子树形式也是同样的形式。注意,有个省略规则,当右子树为空可以省略,或者当左右子树都为空都可以省略。

解题方法

方法一:先序遍历

题目中也说了,这个是个前序遍历。难点在于括号存在不存在的问题。有以下思路:

  1. 对于左子树,如果左孩子或者右孩子存在,那么左子树一定有括号;如果左右子树都不存在,那么为空字符串
  2. 对于右子树,如果右子树存在,则是有括号的;如果有子树不存在,那么就是空字符串;
  3. 最后的结果是根节点的值加上左右子树的字符串
# 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 ''
        subleft = '({})'.format(self.tree2str(t.left)) if t.left or t.right else ''
        subright = '({})'.format(self.tree2str(t.right)) if t.right else ''
        return '{}{}{}'.format(t.val, subleft, subright)

日期

2018 年 1 月 21 日
2018 年 11 月 11 日 —— 剁手节快乐

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值