1.问题描述
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
Note: The merging process must start from the root nodes of both trees.
[来自 <https://leetcode.com/problems/merge-two-binary-trees/description/>](%E6%9D%A5%E8%87%AA%20%3Chttps://leetcode.com/problems/merge-two-binary-trees/description/%3E)
2.问题分析
将两个二叉树进行合并,两树中同一位置都存在节点,则将两个节点值叠加,同一位置的不存在节点的,则将另一个树的节点添加到该位置,否则保留原来节点。
对这个问题,首先想到的是用什么样的方法同时遍历两个树,才能保证每次到达的节点序号一样。最能想到的是利用层序遍历,一层层来,但是对于空结点无能为力,层序遍历并不能识别空结点,人为假如空结点比较繁琐。往递归的方向思考,归纳出共性:
1.父节点都存在,则
父结点相叠加,
若其同侧叶子节点均存在,则递归调用,
若目地二叉树儿子节点不存在,则把源二叉树的儿子节点连接过来
2.目的二叉树父节点不存在,则
将当前源父节点赋给目的父结点
3.c++代码
//我的代码:(beats 95%)
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2)
{
if (t1 != NULL&&t2 != NULL)
{
t1->val += t2->val;
if (t1->left != NULL&&t2->left != NULL)
{
mergeTrees(t1->left, t2->left);
}
else if (t1->left == NULL&&t2->left != NULL)
t1->left = t2->left;
if (t1->right != NULL&&t2->right != NULL)
{
mergeTrees(t1->right, t2->right);
}
else if (t1->right == NULL&&t2->right != NULL)
{
t1->right = t2->right;
}
}
else if (t1 == NULL)
t1 = t2;
return t1;
}