标签:tco == ios 链接 name logs ref names github
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/
欢迎讨论和交流!
标签:tco == ios 链接 name logs ref names github
原文地址:https://www.cnblogs.com/chouxianyu/p/13377638.html