mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
add 617. Merge Two Binary Trees 🍺
This commit is contained in:
parent
9a805cb1d4
commit
6b14ded853
@ -321,6 +321,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。
|
||||
| 572 |[Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)|[C++](solutions/572.%20Subtree%20of%20Another%20Tree.md)|Easy| |
|
||||
| 581 |[Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/581.%20Shortest%20Unsorted%20Continuous%20Subarray.md)|Easy| |
|
||||
| 605 |[Can Place Flowers](https://leetcode.com/problems/can-place-flowers)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/605.%20Can%20Place%20Flowers.md)|Easy| |
|
||||
| 617 |[Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)|[C++](solutions/617.%20Merge%20Two%20Binary%20Trees.md)|Easy| |
|
||||
| 628 |[Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/628.%20Maximum%20Product%20of%20Three%20Numbers.md)|Easy| |
|
||||
| 643 |[Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/643.%20Maximum%20Average%20Subarray%20I.md)|Easy| |
|
||||
| 661 |[Image Smoother](https://leetcode.com/problems/image-smoother)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/661.%20Image%20Smoother.md)|Easy| |
|
||||
|
24
solutions/617. Merge Two Binary Trees.md
Normal file
24
solutions/617. Merge Two Binary Trees.md
Normal file
@ -0,0 +1,24 @@
|
||||
# [617. Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)
|
||||
|
||||
# 思路
|
||||
|
||||
合并两个二叉树。就是一个很简单的递归:
|
||||
* 若`t1`和`t2`任意一个为空,那么直接返回另一个即可(递归出口);
|
||||
* 否则,将`t1`的值加上`t2`的值,然后递归合并`t1`和`t2`的左子树以及`t1`和`t2`的右子树。
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
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);
|
||||
delete t2;
|
||||
return t1;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user