Merge Two Binary Trees

本文解析了一道关于二叉树合并的编程题,详细介绍了题目的要求及解决思路,并给出了具体的Python实现代码。通过递归的方式实现了两棵树的节点值相加合并。

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

     这个题被标记为easy,还是挺简单的,但因为我才入门,其实也碰到了一些问题

  题目要求:

     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.

  思路:

      递归遍历整个树,相同节点的节点值相加作为新的节点

  代码:

      

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def mergeTrees(self, t1, t2):
10         """
11         :type t1: TreeNode
12         :type t2: TreeNode
13         :rtype: TreeNode
14         """
15         if not t1 and not t2:
16             return None
17         val = (t1.val if t1 else 0) + (t2.val if t2 else 0)
18         root = TreeNode(val)
19         root.left = self.mergeTrees(t1 and t1.left, t2 and t2.left)
20         root.right = self.mergeTrees(t1 and t1.right, t2 and t2.right)
21         return root

 

   感受: 

      1、 在写完代码之后去看了看别人的代码,感觉他们的要简洁一些,我的代码中的变量val没必要

      2、 对 and, or的理解: 起初我以为and就是两个为真就返回Ture之类的,今天在看了大神的代码之后发现我这么理解是错误的,下面附上一张图

        

        顺便说一下,and 的优先级大于 or,   

      3、关于类中变量的理解:主要是类变量和对象变量。带有self都是对象变量,唯对象专属,对象可以在类外声明,而类变量由类拥有,被所有对象共享。

      4、在python中似乎不支持三目运算符(?:) 但是我们可以使用:

        为真时的结果 if 判定条件 else 为假时的结果  

      5、在遍历root.left, root.right的时候我的参数里面是没有t1 and t1.val 的,只有t1.val,那四个都是这样写的,最终程序报错,是因为我没有考虑到如果当前t1不存在的情况,和那个val后面为什么要用一个选择是一样的

 

      

转载于:https://www.cnblogs.com/liuxinzhi/p/7468456.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值