617. Merge Two Binary Trees 、136. Single Number(C++、Python)

。_饼干妹妹 提交于 2020-01-31 04:04:53

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!