利用python and or,if else 简化代码

原题是这样的

链接:https://leetcode.com/problems/merge-two-binary-trees/#/description

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree

中文意思大概是:两个二叉树,把它两重叠起来,如果碰上相同不位两个叶子不为空,就把两个值加起来,如果其中一个为空,则值为另外一个不为空的


python 中

一条语句,a and b  如果 a 不为空,则继续检查b,如果a为空那么直接返回 fasle

a or b 若a不为空,直接返回a,否则继续检查下一个

(a if 1 else b)  利用这样的句式可以简化代码(原来都在lambda中用,发现直接用也可以 比如 f=lambda x:a if 1 else 0)

题中预先给了一个定义

# 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 mergeTrees(self, t1, t2):
        if not t1 and not t2:
            return None
        ans=TreeNode((t1.val if t1 else 0)+(t2.val if t2 else 0))
        ans.left=self.mergeTrees(t1 and t1.left,t2 and t2.left)
        ans.right=self.mergeTrees(t1 and t1.right,t2 and t2.right)
        return ans

思路很简单,按照先序递归(不懂请百度先序遍历。。。),写python 重点是效率拉。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值