【Leetcode】Merge Two Binary Trees 合并两个二叉树
2017-10-27 21:26
507 查看
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:
![](https://img-blog.csdn.net/20171027212531698?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd3V0aW5neWVoZQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
Note: The merging process must start from the root nodes of both trees.
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:
Note: The merging process must start from the root nodes of both trees.
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} t1 * @param {TreeNode} t2 * @return {TreeNode} */ var mergeTrees = function(t1, t2) { node = null return mergeTrees2(t1, t2, node) }; function mergeTrees2(t1, t2, node) { if(t1 != null && t2 != null) { node = new TreeNode(t1.val+t2.val) node.left = mergeTrees2(t1.left, t2.left, node.left) node.right = mergeTrees2(t1.right, t2.right, node.right) }else { node = t1 || t2 } return node }
相关文章推荐
- LeetCode--Merge Two Binary Trees(合并两个二叉树)Python
- LeetCode 617 Merge Two Binary Trees(递归合并二叉树)
- Merge Two Binary Trees(合并两个二叉树)
- [LeetCode] Merge Two Binary Trees 合并二叉树
- leetcode Merge Two Binary Trees 合并二叉树
- Leetcode 617 Merge Two Binary Trees 二叉树
- LeetCode 617. Merge Two Binary Tree (合并两个二叉树)
- leetcode 617. Merge Two Binary Trees 二叉树合并 + 深度优先遍历DFS
- Leetcode 21 Merge Two Sorted Lists 将两个已排序的链表合并起来
- Leetcode Merge Two Sorted Lists 合并两个有序链表
- 【leetcode】 Merge Two Binary Trees
- LeetCode - Merge Two Binary Trees
- LeetCode--Merge Two Sorted Lists(合并两个有序链表)Python
- LeetCode | Merge Two Sorted Lists(合并两个链表)
- The Solution to Leetcode 617 Merge Two Binary Trees
- Leetcode代码学习周记——Merge Two Binary Trees
- 【Leetcode-easy-617】Merge Two Binary Trees
- leetcode 617. Merge Two Binary Trees(C语言,二叉树求和,递归)53
- Merge Two Binary Trees(leetcode)
- [LeetCode]Merge Two Sorted Lists & Remove Duplicates from Sorted List 两个有序链表合并为一个&删除链表重复元素