Skip to content

Commit 5110fab

Browse files
authored
Create merge-two-binary-trees.py
1 parent 44a7af3 commit 5110fab

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Python/merge-two-binary-trees.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
# Given two binary trees and imagine that
5+
# when you put one of them to cover the other,
6+
# some nodes of the two trees are overlapped
7+
# while the others are not.
8+
#
9+
# You need to merge them into a new binary tree.
10+
# The merge rule is that if two nodes overlap,
11+
# then sum node values up as the new value of the merged node.
12+
# Otherwise, the NOT null node will be used as the node of new tree.
13+
#
14+
# Example 1:
15+
# Input:
16+
# Tree 1 Tree 2
17+
# 1 2
18+
# / \ / \
19+
# 3 2 1 3
20+
# / \ \
21+
# 5 4 7
22+
# Output:
23+
# Merged tree:
24+
# 3
25+
# / \
26+
# 4 5
27+
# / \ \
28+
# 5 4 7
29+
30+
# Note: The merging process must start from the root nodes of both trees.
31+
32+
# Definition for a binary tree node.
33+
# class TreeNode(object):
34+
# def __init__(self, x):
35+
# self.val = x
36+
# self.left = None
37+
# self.right = None
38+
39+
class Solution(object):
40+
def mergeTrees(self, t1, t2):
41+
"""
42+
:type t1: TreeNode
43+
:type t2: TreeNode
44+
:rtype: TreeNode
45+
"""
46+
if t1 is None:
47+
return t2
48+
if t2 is None:
49+
return t1
50+
t1.val += t2.val
51+
t1.left = mergeTrees(t1.left, t2.left)
52+
t1.right = mergeTrees(t1.right, t2.right)
53+
return t1

0 commit comments

Comments
 (0)