Given binary trees and imagine that's when you put one of the them to cover the other, some nodes of the and trees is Overl Apped while the others is not.
You need to the merge them into a new binary tree. The merge rule is so if the nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the not NULL node would be used as the node of the new tree.
Example 1:
Input: Tree 1 Tree 2 1 2 /\ /\ 3 2 1 3 / \ \ 5 4 7 Output: merged tree: 3 / 4 5 /\ \ 5 4 7
Note: The merging process must start from the root nodes of both trees.
/** * 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) { if (t1==null) { return t2; } if (t2==null) { return t1; } TreeNode res=new TreeNode (t1.val+t2.val); Res.left=mergetrees (t1.left,t2.left); Res.right=mergetrees (t1.right,t2.right); return res; /* */ }}
Java---Merge Binary Trees