1. 程式人生 > >LeetCode617:Merge Two Binary Trees

LeetCode617: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.

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

 

Note: The merging process must start from the root nodes of both trees.


LeetCode:連結

合併兩個二叉樹當然就是同步遍歷了,對於相同位置上的一對結點n1和n2,處理策略是:

  • 若n1和n2都存在,則只需要保留其中一個結點(如n1),將另一結點的值加到此結點上即可(如n1.val += n2.val)。
  • 若n1或n2任一不存在,則合併後的二叉樹對應位置上的結點就是存在的那個了。
  • 若n1和n2都不存在,則合併後仍不存在。

所以我們可以假定第一顆樹為“主樹”,第二顆樹為“從樹”:碰到對應位置上“主樹”結點存在且“從樹”結點存在,則將“從樹”結點值加到“主樹”;碰到對應位置上“主樹”結點存在而“從樹”結點不存在,則不作任何處理;碰到對應位置上“主樹”結點不存在而“從樹”結點存在,則將“從樹”結點移到“主樹”對應位置下。

因為涉及到結點的更新,所以用遞迴會是一個簡單而又方便的方法。

# 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 not t1:
            return t2
        if not t2:
            return t1 
        # 結點重疊時
        if t1 and t2:
            t1.val += t2.val
            t1.left = self.mergeTrees(t1.left, t2.left)
            t1.right = self.mergeTrees(t1.right, t2.right)
        return t1