此篇文章為我的解題紀錄,程式碼或許並不是很完善

Leetcode - 617. Merge Two Binary Trees

解題思路

使用recusive來將每個子節點相加到第一個樹,若是第一個樹在該位置無節點則創建新的點

我滴程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == NULL && root2 == NULL)
{
return NULL;
}
else if (root1 == NULL)
{
return root2;
}
else if (root2 == NULL)
{
return root1;
}
else
{
root1->val += root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
}
return root1;
}
};