# Merge Binary Trees

![](/files/xyPE1vf77j14JWU0k3IF)

* n, h

```jsx
// This is an input class. Do not edit.
class BinaryTree {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

exports.BinaryTree = BinaryTree;

function mergeBinaryTrees(tree1, tree2) {
  
  return mergeHelper(tree1, tree2)
}

function mergeHelper(tree1, tree2) {
  if (tree1 === null && tree2 === null) {
    return null;
  }

  if (tree1 === null) {
    return tree2;
  }

  if (tree2 === null) {
    return tree1;
  }

  tree1.value += tree2.value;
  const left = mergeHelper(tree1.left, tree2.left);
  const right = mergeHelper(tree1.right, tree2.right);

  tree1.left = left;
  tree1.right = right;

  return tree1;
}

// Do not edit the line below.
exports.mergeBinaryTrees = mergeBinaryTrees;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/merge-binary-trees.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
