LeetCode@Tree_617_Merge_Two_Binary_Trees
来源:互联网 发布:广州宏强网络 编辑:程序博客网 时间:2024/06/07 17:01
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:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode mergeTrees(TreeNode t1, TreeNode t2){TreeNode t = null;if(t1 == null && t2 ==null) return null;else if(t1 == null) return t2;else if(t2 == null) return t1;t = new TreeNode(t1.val+t2.val);t.left = mergeTrees(t1.left, t2.left);t.right = mergeTrees(t1.right, t2.right);return t;}}
阅读全文
0 0
- LeetCode@Tree_617_Merge_Two_Binary_Trees
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- SqlServer中循环和条件语句示例!
- Uploadify 3.2 参数属性、事件、方法函数详解
- cocoa touch
- 【数据库-SQL Server】IDispatch error #3092
- 第一次使用Android Studio时你应该知道的一切配置(二):新建一个属于自己的工程并安装Genymotion模拟器
- LeetCode@Tree_617_Merge_Two_Binary_Trees
- github中配置SSHKEY
- Android图片查看(一)
- SQL四种语言:DDL,DML,DCL,TCL
- 还是应该留在这里
- 第一次使用Android Studio时你应该知道的一切配置
- Windows下Tomcat的安装与启动过程
- 广播
- 树套树 bzoj3110&&bzoj3295