0617.cpp (635B)
1 class Solution { 2 public: 3 TreeNode *mergeTrees(TreeNode *root1, TreeNode *root2) { 4 if (!root1 && !root2) return nullptr; 5 if (!root2) 6 return new TreeNode(root1->val, mergeTrees(root1->left, nullptr), 7 mergeTrees(root1->right, nullptr)); 8 if (!root1) 9 return new TreeNode(root2->val, mergeTrees(nullptr, root2->left), 10 mergeTrees(nullptr, root2->right)); 11 return new TreeNode(root1->val + root2->val, mergeTrees(root1->left, root2->left), 12 mergeTrees(root1->right, root2->right)); 13 } 14 };