Problem Statement: 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.
My solution for the problem:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
// in case if either is null, directly return one of the nodes depending on the availablity.
if(t1==null) return t2;
if(t2==null) return t1;
TreeNode left=mergeTrees(t1.left,t2.left);
TreeNode right=mergeTrees(t1.right,t2.right);
t1.val=t1.val+t2.val;
t1.left=left;
t1.right=right;
t2=null;
return t1;
}
}
I have calculated the worst-case time-complexity
of the above code as O(Min.(Size of t1,Size of t2))
but I am not sure about it? Please share your analysis of it.