Merge Two Binary Trees 解法
2017-12-05 20:24
489 查看
Merge Two Binary Trees 解法
第八周题目难度:Easy
LeetCode题号:617
题目
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.
思考
这道题目给了我们两个二叉树,要我们合并两个二叉树,合并的树的每一个点的值等于两个二叉树相对位置的点的值的合。利用recursively call来实现,我们来分析一下。对于每一个新的点的值,我们需要做的就是把两个树中的同样位置的点的值相加。然后recursively来继续代入mergeTrees,左边的点,就代入同样位置两个点的左边。右边的点就代入同样位置的两个点的右边,直到代入得两个点都是null,就停止代入,return回去。 那么对于每一个新的点,有三种情况:1- 两个点都是null,就直接return; 2- 两个点都不是null,直接相加;3- 两个点其中有一个点是null,那么就取另外一个点的值。 需要注意的是,对于每一个新的点,如果代入的两个点其中一个是null的话,那么这个null的点的 .left 和.right 是error。所以要先initial 一下。代码
class Solution { public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { TreeNode root; TreeNode left_1=null, left_2=null; TreeNode right_1=null, right_2=null; if (t1==null && t2==null) { return null; } else if (t1!=null && t2!=null) { root = new TreeNode(t1.val + t2.val); left_1 = t1.left; left_2 = t2.left; right_1 = t1.right; right_2 = t2.right; } else if (t1!=null && t2==nll) { root = new TreeNode(t1.val); left_1 = t1.left; right_1 = t1.right; } else { root = new TreeNode(t2.val); left_2 = t2.left; right_2 = t2.right; } mergeTrees(left_1, left_2); mergeTrees(right_1, right_2); return root; } }
相关文章推荐
- Merge Two Binary Trees问题及解法
- leetcode 617:Merge Two Binary Trees
- leetcode617: Merge Two Binary Trees
- LeetCode 617 Merge Two Binary Trees(递归合并二叉树)
- leetcode[Merge Two Binary Trees]
- 第11周Merge Two Binary Trees
- lintcode/leetcode由易至难第15题:Merge Two Binary Trees
- 617. Merge Two Binary Trees的C++解法
- LC- Merge Two Binary Trees
- 【LeetCode大法】Merge Two Binary Trees
- 617. Merge Two Binary Trees
- Merge Two Binary Trees
- leetcode 617 merge two binary trees
- LeetCode@Tree_617_Merge_Two_Binary_Trees
- 【Leetcode】【python】Hamming Distance, Merge Two Binary Trees
- leetcode(617). Merge Two Binary Trees
- leetcode 617 Merge Two Binary Trees
- LeetCode-617-Merge Two Binary Trees-E
- Merge Two Binary Trees(合并两个二叉树)
- Merge Two Binary Trees [LeetCode 617]