LeetCode617 Merge Two Binary Trees

文章目录
  1. 1. 题目
  2. 2. 思路
  3. 3. 代码

题目

LeetCode617 Merge Two Binary Trees

思路

二叉树的合并.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 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 && t2) {
t1->val += t2->val;
t1->left = mergeTrees(t1->left, t2->left);
t1->right = mergeTrees(t1->right, t2->right);
return t1;
} else return t1 ? t1 : t2;
}
};
分享到 评论