题解 | #合并二叉树#
合并二叉树
https://www.nowcoder.com/practice/7298353c24cc42e3bd5f0e0bd3d1d759
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
对于二叉树的处理,就是心中有一颗小的二叉树,分别是根节点和左右子节点,之后,就是不断地循环即可。
若入口参数有n个,那就是2的n次方。所以说,若是有3个参数,就是及其复杂。同时,
由于是二叉树,一般有左右两个节点,有两个参数的情况也就比较常见。
这个时候,就是需要对出口进行判断,一般都是nullptr为出口函数,
而两者都不为空的,就是会进入下一层,以实现递归。
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
// write code here
if (t1 == nullptr && t2 == nullptr)
return nullptr;
else if (t1 != nullptr && t2 == nullptr)
return t1;
else if (t1 == nullptr && t2 != nullptr)
return t2;
else {
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
}
}
};
查看15道真题和解析
小红书公司福利 950人发布
