mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
24 lines
736 B
Markdown
24 lines
736 B
Markdown
![]() |
# [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;
|
||
|
}
|
||
|
};
|
||
|
```
|