LeetCode617合并二叉树

题目链接

https://leetcode-cn.com/problems/merge-two-binary-trees/

题解

  • 递归解法
  • 解法见代码注释
// Problem: LeetCode 617
// URL: https://leetcode-cn.com/problems/merge-two-binary-trees/
// Tags: Tree Recursion
// Difficulty: Easy

#include <iostream>
using namespace std;

struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};

class Solution{
private:
    // 将树t1和t2合并至t1,并返回t1
    TreeNode* heleper(TreeNode* t1, TreeNode* t2){
        // 两个空树,返回null
        if(t1==nullptr && t2==nullptr)
            return nullptr;
        // 仅t2为空树,不需合并,直接返回t1即可
        else if(t1!=nullptr && t2==nullptr){
            return t1;
        }
        // 仅t1为空树,不需合并,直接返回t2即可
        else if(t1==nullptr && t2!=nullptr){
            return t2;
        }
        // t1和t2均非空
        else{
            t1->val += t2->val;  // 合并根结点
            t1->left = heleper(t1->left, t2->left);  // 合并左子树
            t1->right = heleper(t1->right, t2->right);  // 合并右子树
            delete t2;  // 释放结点
            return t1;
        }
    }

public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        return heleper(t1,t2);
    }
};

作者:@臭咸鱼

转载请注明出处:https://www.cnblogs.com/chouxianyu/

欢迎讨论和交流!


posted @ 2020-07-25 18:02  臭咸鱼  阅读(95)  评论(0编辑  收藏  举报