mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2026-08-31 04:07:21 +08:00
add 617. Merge Two Binary Trees 🍺
This commit is contained in:
@@ -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;
|
||||
}
|
||||
};
|
||||
```
|
||||
Reference in New Issue
Block a user