Tutorialspoint
Problem
Solution
Submissions

Merge Two Binary Trees

Certification: Basic Level Accuracy: 75% Submissions: 4 Points: 5

Write a Java program to merge two binary trees. The merging rule is that if two nodes overlap, then sum the node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of the new tree.

Example 1
  • Input:
    • root1 = [1,3,2,5]
    • root2 = [2,1,3,null,4,null,7]
  • Output: [3,4,5,5,4,null,7]
  • Explanation:
    • Merged tree:

       Merge Two Binary Trees Merged With Null values

    • Merging Process:

      - Root: 1 + 2 = 3
      - Left child: 3 + 1 = 4
      - Right child: 2 + 3 = 5
      - Left-left: 5 + null = 5
      - Left-right: null + 4 = 4
      - Right-right: null + 7 = 7
Example 2
  • Input:
    • root1 = [1]
    • root2 = [1,2]
  • Output: [2,2]
  • Explanation:
    • Merged tree:

      Merge Two Binary Trees Merged

    • Merging Process:

      - Root: 1 + 1 = 2
      - Left child: null + 2 = 2
Constraints
  • The number of nodes in both trees is in the range [0, 2000].
  • -10^4 ≤ Node.val ≤ 10^4
  • Time Complexity: O(n), where n is the minimum number of nodes in the two trees.
  • Space Complexity: O(h), where h is the height of the trees.
Binary TreeeBayPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive approach to traverse both trees simultaneously.
  • If both nodes are present, sum their values and create a new node.
  • If only one node is present, use that node for the merged tree.
  • Recursively merge the left and right subtrees.
  • Return the merged tree root.

Steps to solve by this approach:

 Step 1: Check if either root1 or root2 is null. If root1 is null, return root2. If root2 is null, return root1.
 Step 2: Create a new node with value equal to the sum of root1.val and root2.val.
 Step 3: Recursively merge the left subtrees of root1 and root2 and assign to the left child of the merged node.
 Step 4: Recursively merge the right subtrees of root1 and root2 and assign to the right child of the merged node.
 Step 5: Return the merged node.

Submitted Code :