617. Merge Two Binary Trees
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to merge two binary trees, root1 and root2. The merging rule is straightforward: if two nodes at the same position in both trees exist (overlap), their values are summed up to form the new node's value. If a node exists in one tree but not the other at a given position, the existing node is used in the merged tree. This process suggests a traversal of both trees simultaneously.
Solution
Merge Two Binary Trees in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
# If the first tree's node is None, return the second tree's node.
# This acts as a base case.
if not root1:
return root2
# If the second tree's node is None, return the first tree's node.
if not root2:
return root1
# If both nodes exist, merge them.
# We modify root1 in-place by summing the values.
root1.val += root2.val
# Recursively merge the left and right subtrees.
root1.left = self.mergeTrees(root1.left, root2.left)
root1.right = self.mergeTrees(root1.right, root2.right)
# Return the merged node (the modified root1).
return root1
Merge Two Binary Trees in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
// If root1 is null, the merged tree is just root2.
if (root1 == null) {
return root2;
}
// If root2 is null, the merged tree is just root1.
if (root2 == null) {
return root1;
}
// If both nodes are non-null, merge them.
// We add the value of root2 to root1 and modify root1 in-place.
root1.val += root2.val;
// Recursively merge the left children and assign the result to root1's left child.
root1.left = mergeTrees(root1.left, root2.left);
// Recursively merge the right children and assign the result to root1's right child.
root1.right = mergeTrees(root1.right, root2.right);
// Return the modified root1.
return root1;
}
}
Merge Two Binary Trees in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
// If one of the nodes is null, return the other one.
// This serves as the base case for the recursion.
if (!root1) {
return root2;
}
if (!root2) {
return root1;
}
// If both nodes are non-null, we merge them.
// We sum the values and modify root1 in-place.
root1->val += root2->val;
// Recursively merge the left subtrees.
root1->left = mergeTrees(root1->left, root2->left);
// Recursively merge the right subtrees.
root1->right = mergeTrees(root1->right, root2->right);
// Return the merged tree (which is the modified root1).
return root1;
}
};
Merge Two Binary Trees in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode | null {
// If root1 is null, the merged tree is simply root2.
if (!root1) {
return root2;
}
// If root2 is null, the merged tree is simply root1.
if (!root2) {
return root1;
}
// If both nodes exist, merge them by summing their values.
// We modify root1 in-place.
root1.val += root2.val;
// Recursively merge the left subtrees.
root1.left = mergeTrees(root1.left, root2.left);
// Recursively merge the right subtrees.
root1.right = mergeTrees(root1.right, root2.right);
// Return the modified root1 which is now the merged tree.
return root1;
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.