Merge Two Binary Trees

Merge Two Binary Trees

题目描述:

将两棵二叉树进行合并;如果都有对应位置节点就将节点上的数值相加;如果均为空则为空;如果只有一个不为空;将不为空的位置合并到结果中。

例子:

具体描述见LeetCode617

解题思路:

利用递归的思路来解题;如果只有一方为空的情况下,返回那个非空的一方节点;如果两个节点都不为空的情况下;将对应位置的值相加后合并左右子树即可。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if (!t1 || !t2) return !t1 ? t2 : t1;
else if (t1 && t2){
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
}
}
};