给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
输入: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 输出: 合并后的树: 3 / \ 4 5 / \ \ 5 4 7
&&与运算
递归调用
long fac(int);//函数声明
int main()
{
int n;//n为需要求阶乘的整数
long y; //y为存放n!的变量
cout << "please input an integer :"; //输入的提示
cin >> n; //输入n
y = fac(n);//调用fac函数以求n!
cout << n << "!=" << y << endl; //输出n!的值
system("pause");
return 0;
}
long fac(int n) //递归函数
{
long f;
if (n<0)
{
cout << "n<0,data error!" << endl; //如果输入负数,报错并以-1作为返回值
f = -1;
}
else if (n == 0 || n == 1) f = 1; //0!和1!的值为1
else f = fac(n - 1)*n;//n>1时,进行递归调用
return f;//将f的值作为函数值返回
}
__________________________________________________最终结果______________________________________
/**
* 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:
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if ( t1 && t2 ) {
TreeNode * root = new TreeNode(t1->val + t2->val);
root->left = mergeTrees(t1->left, t2->left);
root->right = mergeTrees(t1->right, t2->right);
return root;
} else {
return t1 ? t1 : t2;
}
}
};