LeetCode 606 Construct String from Binary Tree 解题报告

题目要求

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.

题目分析及思路

给出一个二叉树,要求创建一个字符串,以前序遍历的顺序包含括号和二叉树中的整数。空结点用空括号对"()"表示。需要注意的一点是:不影响一一对应关系的空括号对要忽略,即当结点的左孩子结点为空时不能忽略。可以使用递归的方法,给出三个条件:1)该结点为空;2)该结点的子结点为空;3)该结点的右孩子结点为空。

python代码

# Definition for a binary tree node.

# class TreeNode:

#     def __init__(self, x):

#         self.val = x

#         self.left = None

#         self.right = None

class Solution:

    def tree2str(self, t: TreeNode) -> str:

        if not t:

            return ""

        if not t.left and not t.right:

            return str(t.val)+""

        if not t.right:

            return str(t.val)+"("+self.tree2str(t.left)+")"

        return str(t.val)+"("+self.tree2str(t.left)+")("+self.tree2str(t.right)+")"

            

        

 

转载于:https://www.cnblogs.com/yao1996/p/10721623.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值