Given the roots of two binary trees. The task is to merge the two trees. The merge rule is that if two nodes overlap, then sum 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.
Note: The merging process must start from the root nodes of both trees.
The idea is to traverse both the given trees in preorderfashion. At each step, check whether the current node exists (NOT null) for both of the trees. If so, add the values and update in the first tree, else return the non-null node(if it exists). Now recursively apply this operation for left and right subtree. At the end, the first tree will represent the merged binary tree.
Output
7 3 5 5 2 10 12
Using Iteration - O(n) Time and O(n) Space
The idea is to traverse both the given trees using a stack. At each step, check whether the current nodes exist (not NULL) for both of the trees. If so, add the values and update in the first tree. Otherwise, if the left child of the first tree exists, push the left children (pair) of both trees onto the stack. If not, append the left child of the second tree to the current node of the first tree. Repeat the same process for the right child pair. If both the current nodes are null, continue with the next node pair from the stack. At the end, the first tree will represent the merged binary tree.