题目:
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.
将两棵树合并,只需要顺序访问就行了。
/**
* 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:
void merge(TreeNode* t1, TreeNode* t2, TreeNode* &root)
{
if(!t1 and !t2)return;
if(t1 != nullptr and t2 != nullptr)
{
root = new TreeNode(t1->val + t2->val);
merge(t1->left, t2->left, root->left);
merge(t1->right, t2->right, root->right);
}
else if(t1)
{
root = new TreeNode(t1->val);
merge(t1->left, t2, root->left);
merge(t1->right, t2, root->right);
}
else
{
root = new TreeNode(t2->val);
merge(t1, t2->left, root->left);
merge(t1, t2->right, root->right);
}
}
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
TreeNode *root = nullptr;
merge(t1, t2, root);
return root;
}
};
本文介绍了一种合并两棵二叉树的算法。当两棵树的节点重叠时,节点值相加作为新节点值;当节点不重叠时,则采用非空节点作为新树的节点。通过递归方式实现,适用于所有二叉树结构。
443

被折叠的 条评论
为什么被折叠?



