简体   繁体   中英

Can someone explain me how merging of two binary trees happen?

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Input:

Tree 1                     Tree 2                  
      1                         2                             
     / \                       / \                            
    3   2                     1   3                        
   /                           \   \                      
  5                             4   7                  

Output: Merged tree:

     3
    / \
   4   5
  / \   \ 
 5   4   7



public class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null)
            return t2;
        if (t2 == null)
            return t1;
        t1.val += t2.val;
        t1.left = mergeTrees(t1.left, t2.left);
        t1.right = mergeTrees(t1.right, t2.right);
        return t1;
    }
}

It may be a naive to ask but how is this algorithm working? Once if we return this t2 or the t1, it returns the other TreeNode, so technically method should stop executing. Isn't it? Help me

mergeTrees only returns "the other TreeNode" when that is the only TreeNode (because one is null), which makes sense because there is nothing left to do on that subtree . But you still need to work your way back; in particular, you need to attach "the other TreeNode" to its new parent, and work down unvisited-as-yet subtrees.

This algo

base case: node t1, t2 or both are null, so that node will be replaced with one of them (easy)

Other case is even more simple, this algorithm visits first the node and then it does the recursion on the left nodes of these 2 trees and then on the right, so it starts from the top (root) and it goes down to the left left node, when it arrives to the leftmost node, it goes to the right node, and at the and you've passed all nodes of your tree.

Only t1 is modified and it will be returned, t2 will be ignored.

https://imgur.com/NyDMFge

If you pay attention to this line: t1.val += t2.val; , you can tell that we're actually merging tree 2 into tree 1. We are not creating a new tree/node.

Also note that we always pass the corresponding nodes of the two trees in function mergeTrees() . If both nodes are non-null, we add the value of t2 to t1 . If any of these is null then, according to the rules, we have to keep the other node (which could be non-null or null).

We return t2 or t1 only when we have processed both left and right subtrees (if any) of current nodes. This return value becomes the child of the t1 node in the previous call of mergeTrees() .

Example:

Tree 1:
  a (single node)

Tree 2:
  b
 /
c

The 1st function call - mergeTrees(a, b) :

  • Here both nodes a and b are non-null. So we do a.val += b.val .
  • Now, a.left will be assigned to the node returned by 2nd function call - mergeTrees(a.left, b.left) .

So we make our 2nd function call - mergeTrees(null, c) :

  • Here the first node is null. So we simply return the other node c

Now, control is back to 1st call:

  • a.left = c
  • We have to assign a.right to the node returned by our 3rd function call - mergeTrees(a.right, b.right)

Time to make the 3rd function call - mergeTrees(null, null) :

  • Here first node is NULL. We return the second node which is also null .

Control is back to 1st call:

  • a.right = NULL
  • We have processed both left and right subtrees. Return a .

The caller now receives the root a of merged trees, which now looks like this:

Merged Tree:

  a
 /
c

Note that node a now stores the value a.val + b.val .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM