Leetcode Python超瑣碎筆記: 617. Merge Two Binary Trees
ofollow,noindex">問題地址 ,難度: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.
Example 1:
Input: Tree 1Tree 2 12 / \/ \ 3213 /\\ 547 Output: Merged tree: 3 / \ 45 / \\ 547
Note: The merging process must start from the root nodes of both trees.
題意分析
這道題屬於一想通就能一下做出來的。首先merge樹的子問題是merge節點/子樹,從根節點開始,返回的結果應作為當前節點的左右子樹;其次merged tree
的結構包含了原始兩個樹的結構,所以可以在任選一個原始樹進行in-place的merge,有的留下或者更新值,沒有的補上(當這棵樹上沒有一個節點/子樹時,把另一棵上對應的節點/子樹接上來)。
樹結構上的遞迴真是無處不在(比如Parser),一旦想清楚,實現出來往往令人覺得優雅而有趣。貼一個做這道題前沒多久做的Golang練習,也是兩個樹之間的問題:判斷二叉查詢樹是否等價 。
我的實現及調優過程
方法1 :100 ms
暫時沒有想到除此以外更好的方法。
# Definition for a binary tree node. # class TreeNode: #def __init__(self, x): #self.val = x #self.left = None #self.right = None class Solution: def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ return merge(t1, t2) def merge(t1, t2): if t1 is None: return t2 elif t2 is None: return t1 else: t1.val = t1.val + t2.val t1.left = merge(t1.left, t2.left) t1.right = merge(t1.right, t2.right) return t1
-
時間複雜度:O(n) (
n
為merged tree
的節點數) - 空間複雜度:O(1) (未建立新變數,但實際上遞迴本身的棧會佔用一些資源)