Recursion
1. update current value
2. recurse left and right
not in-place
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if not t1 and not t2: return None
if not t1:
left = self.mergeTrees(None, t2.left)
right = self.mergeTrees(None, t2.right)
value = t2.val
elif not t2:
left = self.mergeTrees(t1.left, None)
right = self.mergeTrees(t1.right, None)
value = t1.val
else:
left = self.mergeTrees(t1.left, t2.left)
right = self.mergeTrees(t1.right, t2.right)
value = t1.val + t2.val
root = TreeNode(value)
root.left = left
root.right = right
return root
some in-place, some not:
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if None in (t1, t2): return t1 or t2
cur = ListNode(t1.val+t2.val)
cur.left = self.mergeTrees(t1.left, t2.left)
cur.right = self.mergeTrees(t1.right, t2.right)
return cur
in-place: write to t1
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if None in (t1, t2): return t1 or t2
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1
Iterative
in-place
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if not t1: return t2
q = collections.deque([t1, t2])
while q:
n1 = q.popleft()
n2 = q.popleft()
if not n2: continue
n1.val += n2.val
if not n1.left:
n1.left = n2.left
else:
q.append(n1.left)
q.append(n2.left)
if not n1.right:
n1.right = n2.right
else:
q.append(n1.right)
q.append(n2.right)
return t1