1. 程式人生 > >617.Merge Two Binary Trees(合併兩棵樹)

617.Merge Two Binary Trees(合併兩棵樹)

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.

您需要將它們合併成一個新的二叉樹。合併規則是如果兩個節點重疊,則sum節點值作為合併節點的新值。否則,NOT空節點將被用作新樹的節點。

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

思路:

考察的就是二叉樹的遍歷,遍歷每個結點然後如果重疊(兩個二叉樹結點都不為空)新結點值便為兩者和,不重疊(只有一個結點為空)新結點值為不為空的值,全為空到達底部返跳出。按照這個邏輯進行迭代

聯想:二叉樹遍歷方式有深度優先和廣度優先,深度(縱向)優先在Python中一般使用列表,廣度優先(橫向)一般使用迭代

# 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):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        # 結點都為空時
        if t1 is None and t2 is None:
            return
        # 只有一個結點為空時
        if t1 is None:
            return t2
        if t2 is None:
            return t1
        # 結點重疊時
        t1.val += t2.val
        # 進行迭代
        t1.right = self.mergeTrees(t1.right, t2.right)
        t1.left = self.mergeTrees(t1.left, t2.left)
        return t1