1、二叉树基本就是涉及到递归问题。
这道题2种思路,一种是直接在其中一棵树上合并另一棵树,一种是创建新树。
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// build a new tree or add t1
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if (!t1 && !t2) {
return NULL;
}
if (!t1) {
return t2;
}
if (!t2) {
return t1;
}
TreeNode* res = new TreeNode(t1->val + t2->val);
res->left = mergeTrees(t1->left, t2->left);
res->right = mergeTrees(t1->right, t2->right);
return res;
}