[LeetCode]#617. Merge Two Binary Trees

Environment: Python 3.8

Key technique: TreeNode

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

Analysis:

I am not so good at data structure and find a way to verify result locally.

  1. Download binarytree module
pip install binarytree

2. You can see your tree as below code.

from binarytree import Nodet1 = Node(1) 
t1.left = Node(3)
t1.right = Node(2)
t1.left.left=Node(5)
# Getting binary tree
print('Binary tree :', t1)
# Getting list of nodes
print('List of nodes :', list(t1))

# Getting inorder of nodes
print('Inorder of nodes :', t1.inorder)

# Checking tree properties
print('Size of tree :', t1.size)
print('Height of tree :', t1.height)

3. Output is as below.

Binary tree : 
1
/ \
3 2
/
5
List of nodes : [Node(1), Node(3), Node(2), Node(5)]
Inorder of nodes : [Node(5), Node(3), Node(1), Node(2)]
Size of tree : 4
Height of tree : 2

4. Use this module to solve this problem

Solution:

class Solution:
def mergeTrees(self, t1, t2):
if t1==None and t2==None:
return None
elif t1==None:
return t2
elif t2==None:
return t1
else:
ans = TreeNode(t1.val+t2.val)
ans.left=self.mergeTrees(t1.left,t2.left)
ans.right=self.mergeTrees(t1.right,t2.right)
return ans

Note: If you use the module, please replace “TreeNode” with Node.

Submissions:

Reference:

https://blog.csdn.net/weixin_38425780/article/details/79700819

Interesting in any computer science.