Skip to content

Commit c3cd255

Browse files
jindal2309shermanhui
authored andcommitted
Added code to merge two trees (TheAlgorithms#4121)
* Added code to merge two trees * Added doctest and type hints * Added pre-commit
1 parent 942acdd commit c3cd255

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#!/usr/local/bin/python3
2+
"""
3+
Problem Description: Given two binary tree, return the merged tree.
4+
The rule for merging is that if two nodes overlap, then put the value sum of
5+
both nodes to the new value of the merged node. Otherwise, the NOT null node
6+
will be used as the node of new tree.
7+
"""
8+
from typing import Optional
9+
10+
11+
class Node:
12+
"""
13+
A binary node has value variable and pointers to its left and right node.
14+
"""
15+
16+
def __init__(self, value: int = 0) -> None:
17+
self.value = value
18+
self.left: Optional[Node] = None
19+
self.right: Optional[Node] = None
20+
21+
22+
def merge_two_binary_trees(tree1: Optional[Node], tree2: Optional[Node]) -> Node:
23+
"""
24+
Returns root node of the merged tree.
25+
26+
>>> tree1 = Node(5)
27+
>>> tree1.left = Node(6)
28+
>>> tree1.right = Node(7)
29+
>>> tree1.left.left = Node(2)
30+
>>> tree2 = Node(4)
31+
>>> tree2.left = Node(5)
32+
>>> tree2.right = Node(8)
33+
>>> tree2.left.right = Node(1)
34+
>>> tree2.right.right = Node(4)
35+
>>> merged_tree = merge_two_binary_trees(tree1, tree2)
36+
>>> print_preorder(merged_tree)
37+
9
38+
11
39+
2
40+
1
41+
15
42+
4
43+
"""
44+
if tree1 is None:
45+
return tree2
46+
if tree2 is None:
47+
return tree1
48+
49+
tree1.value = tree1.value + tree2.value
50+
tree1.left = merge_two_binary_trees(tree1.left, tree2.left)
51+
tree1.right = merge_two_binary_trees(tree1.right, tree2.right)
52+
return tree1
53+
54+
55+
def print_preorder(root: Optional[Node]) -> None:
56+
"""
57+
Print pre-order traversal of the tree.
58+
59+
>>> root = Node(1)
60+
>>> root.left = Node(2)
61+
>>> root.right = Node(3)
62+
>>> print_preorder(root)
63+
1
64+
2
65+
3
66+
>>> print_preorder(root.right)
67+
3
68+
"""
69+
if root:
70+
print(root.value)
71+
print_preorder(root.left)
72+
print_preorder(root.right)
73+
74+
75+
if __name__ == "__main__":
76+
tree1 = Node(1)
77+
tree1.left = Node(2)
78+
tree1.right = Node(3)
79+
tree1.left.left = Node(4)
80+
81+
tree2 = Node(2)
82+
tree2.left = Node(4)
83+
tree2.right = Node(6)
84+
tree2.left.right = Node(9)
85+
tree2.right.right = Node(5)
86+
87+
print("Tree1 is: ")
88+
print_preorder(tree1)
89+
print("Tree2 is: ")
90+
print_preorder(tree2)
91+
merged_tree = merge_two_binary_trees(tree1, tree2)
92+
print("Merged Tree is: ")
93+
print_preorder(merged_tree)

0 commit comments

Comments
 (0)