617.题目链接:Merge Two Binary Trees
C++
//C++
//Approach #1 Using Recursion
//时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1==nullptr)return t2;
if(t2==nullptr)return t1;
t1->val+=t2->val;
t1->left=mergeTrees(t1->left,t2->left);
t1->right=mergeTrees(t1->right,t2->right);
return t1;
}
};
Python
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if t1 == None:
return t2
if t2 == None:
return t1
t1.val+=t2.val
t1.left = self.mergeTrees(t1.left,t2.left)
t1.right = self.mergeTrees(t1.right,t2.right)
return t1
136. 136. Single Number
直接采用异或操作,如果两个数相同则异或值为0
C++
class Solution{
public:
int singleNumber(vector<int>& nums){
int ans;
ans=nums[0];
for(int i=1;i<nums.size();i++)
{
ans=ans^nums[i];
}
return ans;
}
};
Python
class Solution:
def singleNumber(self, nums:List[int])-> int:
ans =nums[0]
for index,i in enumerate(nums):
if index == 0:continue
ans^=nums[index]
return ans
来源:CSDN
作者:xxzccccccc
链接:https://blog.csdn.net/baidu_32048673/article/details/104115274