Leetcode 617. Merge Two Binary Trees Sure! Let’s break down the problem step-by-step.
You are given two binary trees root1
and root2
. Imagine that when you put one of them to cover the other, some nodes of the two trees overlap while others do not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum their values as the new value of the merged node. Otherwise, the non-null node will be used as the node of the new tree.
Return the merged tree.
Example:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
nullptr
.mergeTrees
that accepts the roots of the two trees.null
, return the other node.null
.#include <iostream>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if (t1 == nullptr) return t2;
if (t2 == nullptr) return t1;
TreeNode* merged = new TreeNode(t1->val + t2->val);
merged->left = mergeTrees(t1->left, t2->left);
merged->right = mergeTrees(t1->right, t2->right);
return merged;
}
};
// Helper function to print the tree (in-order traversal)
void printTree(TreeNode* node) {
if (node == nullptr) {
return;
}
printTree(node->left);
std::cout << node->val << " ";
printTree(node->right);
}
int main() {
// Create test trees
TreeNode* tree1 = new TreeNode(1);
tree1->left = new TreeNode(3);
tree1->right = new TreeNode(2);
tree1->left->left = new TreeNode(5);
TreeNode* tree2 = new TreeNode(2);
tree2->left = new TreeNode(1);
tree2->right = new TreeNode(3);
tree2->left->right = new TreeNode(4);
tree2->right->right = new TreeNode(7);
// Merge trees
Solution s;
TreeNode* mergedTree = s.mergeTrees(tree1, tree2);
// Print the merged tree
std::cout << "Merged Tree: ";
printTree(mergedTree); // Expected output: 5 4 4 3 5 7
return 0;
}
This code merges the two binary trees as described and prints the merged tree using an in-order traversal to verify the solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?