13.Merge Two Binary Trees
Solution: (Using Stack)
Algorithm:
Create a stack
Push the root nodes of both the trees onto the stack.
While the stack is not empty, perform following steps :
Pop a node pair from the top of the stack
For every node pair removed, add the values corresponding to the two nodes and update the value of the corresponding node in the first tree
If the left child of the first tree exists, push the left child(pair) of both the trees onto the stack.
If the left child of the first tree doesn’t exist, append the left child of the second tree to the current node of the first tree
Do same for right child pair as well.
If both the current nodes are NULL, continue with popping the next nodes from the stack.
Return root of updated Tree
Last updated