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.
Tree 1 Tree 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
/ \ \
5 4 7
I am not so good at data structure and find a way to verify result locally.
- 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)
# 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 :
5List 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
def mergeTrees(self, t1, t2):if t1==None and t2==None:
ans = TreeNode(t1.val+t2.val)
Note: If you use the module, please replace “TreeNode” with Node.
Binarytree Module in Python - GeeksforGeeks
A binary tree is a data structure in which every node or vertex has atmost two children. In Python, a binary tree can…