LeetCode617合并二叉树

题目链接

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

题解

  • 递归解法
  • 解法见代码注释
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 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/

欢迎讨论和交流!