题解 | #合并二叉树#

合并二叉树

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;
        }
    }
};

全部评论

相关推荐

牛客41406533...:回答他在课上学,一辈子待在学校的老教授用三十年前的祖传PPT一字一句的讲解,使用谭浩强红皮书作为教材在devc++里面敲出a+++++a的瞬间爆出114514个编译错误来学这样才显得专业
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务