617. Merge Two Binary Trees (合並兩個二叉樹)by python


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.

給兩個二叉樹想要合並,有一些結點會重疊而有一些不會,現在想把重疊的結點值變為兩者值相加,不重疊的直接用,構建出新的樹

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.

合並都從兩個二叉樹根部開始

思路:

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

聯想:二叉樹遍歷方式有深度優先和廣度優先,深度(縱向)優先在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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM