LeetCode 617. Merge Two Binary Trees

题目链接:https://leetcode.com/problems/merge-two-binary-trees/description/

题目解析:将T1作为模板,把T2合进来。容易想到的是用递归的方法遍历子树,主要分成三种情况——

  • T1和T2当前节点都存在,那么两者值相加即可,继续分别递归左右子树;
  • T1不存在,T2存在,那么把T1当前空节点赋值为T2当前节点即可,以T2当前节点为根结点的子树自然会合并到T1上;
  • T1存在,T2不存在,那么只要返回即可,不用进行任何操作。

代码如下:20ms Accepted beating 100%

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if (t1 != NULL && t2 != NULL)
        {
            t1->val = t1->val + t2->val;
            t1->right = mergeTrees(t1->right, t2->right);
            t1->left = mergeTrees(t1->left, t2->left);
            return t1;
        }
        else if (t2 != NULL)
        {
            t1 = t2;
            return t1;
        }
        else
            return t1;
    }
};

static const auto ____ = [] () {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();

猜你喜欢

转载自blog.csdn.net/github_36324732/article/details/81194933