文章目录
- 1. 题目
- 2. 递归解题
1. 题目
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:输入: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7
输出:
合并后的树:3/ \4 5/ \ \ 5 4 7
注意: 合并必须从两个树的根节点开始。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-binary-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 递归解题
class Solution {
public:TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {if(!t1 && !t2)return NULL;TreeNode *node = new TreeNode(0);if(t1 && !t2){node->val = t1->val;node->left = t1->left;node->right = t1->right;}else if(!t1 && t2){node->val = t2->val;node->left = t2->left;node->right = t2->right;}else//两个树种节点都存在{node->val = t1->val + t2->val;node->left = mergeTrees(t1->left, t2->left);node->right = mergeTrees(t1->right, t2->right);}return node;}
};
class Solution {// c++ 2020.9.23
public:TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {if(!t1) return t2;if(!t2) return t1;auto l = mergeTrees(t1->left, t2->left);auto r = mergeTrees(t1->right, t2->right);t1->val += t2->val;t1->left = l;t1->right = r;return t1;}
};
class Solution: # py3def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:if not t1:return t2elif not t2:return t1l = self.mergeTrees(t1.left, t2.left)r = self.mergeTrees(t1.right, t2.right)t1.val += t2.valt1.left = lt1.right = rreturn t1
100 ms 14.5 MB