Description
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.
Example 1:
1 | Input: |
Note: The merging process must start from the root nodes of both trees.
分析
合并两棵二叉树,如果节点有交集则两个节点的和作为新节点,否则非空节点作为新节点。
从两棵树的 root 节点开始合并,假设合并到了某个节点 t,则考虑如下情况:
如果 t1 和 t2 都不为 null,那么
1
2
3
4t.val = t1.val + t2.val;
t.left = 递归(t1.left, t2.left);
t.right = 递归(t1.right, t2.right);
return t;
如果 t1 为 null,那么返回 t2
如果 t2 为 null,那么返回 t1
Solution
根据分析,写出代码如下:
1 | /** |
一遍过,bugfree~~