经典先序或后序递归即可。
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (!root1 && !root2) {
return nullptr;
} else if (!root1) {
return root2;
} else if (!root2) {
return root1;
}
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
root1->val += root2->val;
return root1;
}
};
class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
if not root1 and not root2:
return None
elif not root1:
return root2
elif not root2:
return root1
root1.left = self.mergeTrees(root1.left, root2.left)
root1.right = self.mergeTrees(root1.right, root2.right)
root1.val += root2.val
return root1