Skip to content

Commit 86290df

Browse files
committed
Merge Two Binary Trees
1 parent 727d815 commit 86290df

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

617-merge-two-binary-trees.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/merge-two-binary-trees/
3+
4+
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
5+
others are not.
6+
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
7+
merged node. Otherwise, the NOT null node will be used as the node of new tree.
8+
9+
Example 1:
10+
Input:
11+
Tree 1 Tree 2
12+
1 2
13+
/ \ / \
14+
3 2 1 3
15+
/ \ \
16+
5 4 7
17+
Output:
18+
Merged tree:
19+
3
20+
/ \
21+
4 5
22+
/ \ \
23+
5 4 7
24+
25+
Note: The merging process must start from the root nodes of both trees.
26+
"""
27+
# Definition for a binary tree node.
28+
# class TreeNode(object):
29+
# def __init__(self, x):
30+
# self.val = x
31+
# self.left = None
32+
# self.right = None
33+
34+
class Solution(object):
35+
def mergeTrees(self, t1, t2):
36+
"""
37+
:type t1: TreeNode
38+
:type t2: TreeNode
39+
:rtype: TreeNode
40+
"""
41+
if t1 is None:
42+
return t2
43+
if t2 is None:
44+
return t1
45+
t1.val += t2.val
46+
t1.left = self.mergeTrees(t1.left,t2.left)
47+
t1.right = self.mergeTrees(t1.right,t2.right)
48+
return t1

0 commit comments

Comments
 (0)