博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode617. Merge Two Binary Trees (思路及python解法)
阅读量:2242 次
发布时间:2019-05-09

本文共 1220 字,大约阅读时间需要 4 分钟。

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.

Example 1:

Input: 	Tree 1                     Tree 2                            1                         2                                      / \                       / \                                    3   2                     1   3                               /                           \   \                            5                             4   7                  Output: Merged tree:	     3	    / \	   4   5	  / \   \ 	 5   4   7

合并两个二叉树,用递归方法很简单。

新建TreeNode的时候注意使用括号,否则计算会出错。

class Solution:    def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:        if not t1 and not t2:return None        node = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0))        node.left = self.mergeTrees(t1 and t1.left, t2 and t2.left)        node.right = self.mergeTrees(t1 and t1.right, t2 and t2.right)        return node

 

转载地址:http://wcrbb.baihongyu.com/

你可能感兴趣的文章
SDO_GEOMETRY结构说明
查看>>
oracle 的 SDO_GEOMETRY
查看>>
往oracle中插入geometry的两种方式
查看>>
Oracle Spatial中的Operator操作子 详细说明
查看>>
Oracle Spatial中SDO_Geometry详细说明
查看>>
oracle 聚合函数 LISTAGG ,将多行结果合并成一行
查看>>
Oracle列转行函数 Listagg() 语法详解及应用实例
查看>>
LISTAGG函数的用法
查看>>
Oracle Spatial操作geometry方法
查看>>
IDEA类和方法注释模板设置(非常详细)
查看>>
Java程序初始化的顺序
查看>>
Dubbo和Spring结合配置文件内容解析为bean的过程
查看>>
fastJson注解@JSONField使用的一个实例
查看>>
fastjson的@JSONField注解的一点问题
查看>>
fastjson使用(三) -- 序列化
查看>>
浅谈使用单元素的枚举类型实现单例模式
查看>>
Java 利用枚举实现单例模式
查看>>
Java 动态代理作用是什么?
查看>>
Java动态代理机制详解(JDK 和CGLIB,Javassist,ASM) (清晰,浅显)
查看>>
三种线程安全的单例模式
查看>>