1. 程式人生 > >Merge Two Binary Trees(easy)

Merge Two Binary Trees(easy)

不存在 root col es2017 運算符 節點 erl des into

     這個題被標記為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)