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:

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.

思路: 左右两棵树同时进行递归访问(根左右),若节点都存在,返回和,若某一棵树的当前节点不存在,则返回另一棵树的当前节点。

JAVA CODE

/**
* 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;
t1.val += t2.val;
t1.left = mergeTrees(t1.left,t2.left);
     // 递归,访问顺序:根左右
t1.right = mergeTrees(t1.right,t2.right);
return t1;
}
}
 

最新文章

  1. 一个java源文件中为什么只能有一个public类。
  2. 【CSS3】 理解CSS3 transform中的Matrix(矩阵)
  3. paip.编程语言到底有没有优劣之分优秀之分
  4. 第一个sprint心得及感想
  5. 九度OJ1084
  6. yum中baserul路径中的空格
  7. [原]Unity3D深入浅出 - 雾效(Fog)
  8. 页面插入Flash方式
  9. website
  10. Problem B: Excuses, Excuses!
  11. Mathematics for Computer Graphics
  12. python 日期格式化常用标记
  13. 简聊iOS支付集成(支付宝和微信支付)
  14. 有关java调用批处理文件
  15. TCP的核心系列 — SACK和DSACK的实现(四)
  16. 抛开rails使用ActiveRecord连接数据库
  17. 关于select 文字居向
  18. 键盘事件(keyup、keydown、keypress)
  19. lambda表达式和表达式树(深入理解c#)
  20. EditText: 自定义EditText 触摸时无法获取焦点

热门文章

  1. python appium 操作app
  2. Day4 - Linux分区规划与xshell使用排错
  3. Southwestern Europe Regional Contest 2014 题解
  4. openssl命令
  5. 前端面试angular 常问问题总结
  6. 创建WIFI热点--附近的百度帐号
  7. 打开safari开发者选项
  8. Python 异常处理
  9. 详解 mpls vpn 的实现
  10. 【★】RSA-什么是不对称加密算法?