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.
解法1:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if not t1 and not t2: return None root = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0)) root.left = self.mergeTrees(t1.left if t1 else None, t2.left if t2 else None) root.right = self.mergeTrees(t1.right if t1 else None, t2.right if t2 else None) return root
更简略的:
def mergeTrees(self, t1, t2): if not t1 and not t2: return None ans = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0)) ans.left = self.mergeTrees(t1 and t1.left, t2 and t2.left) ans.right = self.mergeTrees(t1 and t1.right, t2 and t2.right) return ans
用and代替if明显是代码更少!
官方解答有错,修改了原有的输入数据:
public class Solution { public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { if (t1 == null) return t2; if (t2 == null) return t1; t1.val += t2.val; t1.left = mergeTrees(t1.left, t2.left); t1.right = mergeTrees(t1.right, t2.right); return t1; } }
如果不用递归而使用迭代,采用队列实现,层序遍历BFS思想,当遇到2颗树对应的节点之一不为null时就需入队,同时在建立新树时也一样将对应的结果节点入队:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ # solution 2 if not t1 and not t2: return None q1, q2 = collections.deque([t1]), collections.deque([t2]) root = TreeNode(0) q = collections.deque([root]) while q1 and q2: node1, node2, node = q1.popleft(), q2.popleft(), q.popleft() node.val = (node1 and node1.val or 0) + (node2 and node2.val or 0) if (node1 and node1.left) or (node2 and node2.left): q1.append(node1 and node1.left) q2.append(node2 and node2.left) node.left = TreeNode(0) q.append(node.left) if (node1 and node1.right) or (node2 and node2.right): q1.append(node1 and node1.right) q2.append(node2 and node2.right) node.right = TreeNode(0) q.append(node.right) return root
空间复杂度O(max(M,N)), M、N为两颗树的节点个数。
注,关于deque可以直接判断其是否为空:
>>> import collections
>>> q=collections.deque([])
>>> if q:
... print "Y"
...
>>> q=collections.deque([1])
>>> if q:
... print "x"
...
x