首页 > 代码库 > [Leetcode] Binary tree -- 617. Merge Two Binary Trees
[Leetcode] Binary tree -- 617. Merge Two Binary Trees
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
Note: The merging process must start from the root nodes of both trees.
Solution:
1. use recursive time complexity o(min(m,n)) m is vertex number of t1, n is the vertex number of t2
#combine the node to left tree t1. If node are overlapped, then add valu to t1.val. else return t1 or t2 if they are null repsectively.
1 if t1 is None: 2 return t2 3 if t2 is None: 4 return t1 5 t1.val += t2.val 6 t1.left = mergeTrees(t1.left, t2.left) 7 t1.right = mergeTrees(t1.right, t2.right) 8 9 return t1
2. use iterative way
1 if t1 is None: 2 return t2 3 st = [] 4 st.append((t1,t2)) 5 while (len(st)): 6 nodes = st.pop() 7 r1 = nodes[0] 8 r2 = nodes[1] 9 if r1 is None or r2 is None: 10 continue 11 r1.val += r2.val 12 st.append((r1.left, r2.left)) 13 st.append((r1.right, r2.right)) 14 15 if r1.left is None and r2.left is not None: 16 r1.left = r2.left 17 if r1.right is None and r2.right is not None: 18 r1.right = r2.right 19 20 return t1
[Leetcode] Binary tree -- 617. Merge Two Binary Trees