DEV Community

almokhtar bekkour
almokhtar bekkour

Posted on

Merge Two Binary Trees by doing Node Sum (Recursive and Iterative) javascript

To merge two binary trees by doing a node sum, you can use either a recursive or an iterative approach. Here is how you could implement this using each approach in JavaScript:

Recursive approach

Create a function that takes two binary trees as arguments and returns their merged tree.

In the function, check if one of the trees is null. If so, return the other tree.

If both trees are non-null, create a new node with the value equal to the sum of the values of the two nodes.
Set the left child of the new node to the result of merging the left children of the two nodes.

Set the right child of the new node to the result of merging the right children of the two nodes.

Return the new node.

Here is an example of what the main parts of your solution might look like:

class Node {
  constructor(value) {
    this.value = value
    this.left = null
    this.right = null
  }
}

function mergeTrees(t1, t2) {
  if (t1 == null) return t2
  if (t2 == null) return t1

  const node = new Node(t1.value + t2.value)
  node.left = mergeTrees(t1.left, t2.left)
  node.right = mergeTrees(t1.right, t2.right)

  return node
}

const t1 = ...
const t2 = ...
const mergedTree = mergeTrees(t1, t2)

// display the merged tree
Enter fullscreen mode Exit fullscreen mode

Top comments (0)