题目中是对两颗二叉树的每个结点进行值得合并,最终返回根节点,则以根节点开始,从上至下递归得出每个结点的左子结点和右子结点的值即可
代码:
class Solution: def mergeTrees(self , t1 , t2 ): # write code here if not t1 and not t2: return None if not t1 and t2: root = TreeNode(t2.val) root.left = self.mergeTrees(None, t2.left) root.right = self.mergeTrees(None, t2.right) if t1 and not t2: root = TreeNode(t1.val) root.left = self.mergeTrees(t1.left, None) root.right = self.mergeTrees(t1.right, None) elif t1 and t2: root = TreeNode(t1.val +t2.val) root.left = self.mergeTrees(t1.left, t2.left) root.right = self.mergeTrees(t1.right, t2.right) return root