码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Two Binary Trees(easy)

时间:2017-09-03 01:08:36      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:简洁   node   程序   感受   others   结果   对象   三目运算   div   

     这个题被标记为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后面为什么要用一个选择是一样的

 

      

Merge Two Binary Trees(easy)

标签:简洁   node   程序   感受   others   结果   对象   三目运算   div   

原文地址:http://www.cnblogs.com/liuxinzhi/p/7468456.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!