Skip to main content

< Back to Data Structures and Algorithms

LeetCode 617 · Trees

Merge Two Binary Trees

Overlays one binary tree on another, summing the values where both have a node and keeping whichever node's there where only one does.

Step through it

Examples
Edge cases
root1
5321
root2
41732

Step 0 of 27

Output

Running… play or step to the end.

The code

/**
 * Definition for a binary tree node.
 * const TreeNode = (val, left, right) => {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root1
 * @param {TreeNode} root2
 * @return {TreeNode}
 */
 const mergeTrees = (root1, root2) => {
  if (!root1) {
      return root2
  } else if (!root2) {
      return root1
  }
  
  root1.val += root2.val
  
  root1.left = mergeTrees(root1.left, root2.left)
  root1.right = mergeTrees(root1.right, root2.right)
      
  return root1
}

View it on GitHub (opens in a new tab)