【Leetcode】【python】Hamming Distance, Merge Two Binary Trees

Hamming Distance

题目大意

两个整数的汉明距离是指其二进制不相等的位的个数。
给定两个整数x和y,计算汉明距离。
注意:
0 ≤ x, y < 2^31.

解题思路

异或运算

代码

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return bin(x ^ y).count('1')

我提交的

class Solution(object):
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        x_bin = list(bin(x))
        y_bin = list(bin(y))
        x_bin.reverse()
        y_bin.reverse()
        x_judge = []
        y_judge = []
        for x in x_bin:
            if x == 'b':
                break    
            x_judge.append(x)
        for y in y_bin:
            if y == 'b':
                break    
            y_judge.append(y)
        list_distance = abs(len(x_judge) - len(y_judge))
        if len(x_judge) < len(y_judge):
            for i in range(list_distance):
                x_judge.append('0')
        else:
            for i in range(list_distance):
                y_judge.append('0')
        distance = 0
        for i in range(len(x_judge)):
            if x_judge[i] != y_judge[i]:
                distance += 1
        return distance 

总结

以后谁和我说二进制异或运算我和谁急

Merge Two Binary Trees

题目大意

给两个二叉树想要合并,有一些结点会重叠而有一些不会,现在想把重叠的结点值变为两者值相加,不重叠的直接用,构建出新的树

解题思路

考察的就是二叉树的遍历,遍历每个结点然后如果重叠(两个二叉树结点都不为空)新结点值便为两者和,不重叠(只有一个结点为空)新结点值为不为空的值,全为空到达底部返跳出。按照这个逻辑进行迭代

联想:二叉树遍历方式有深度优先和广度优先,深度(纵向)优先在Python中一般使用列表,广度优先(横向)一般使用迭代

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def mergeTrees(self, t1, t2):
        """
        :type t1: TreeNode
        :type t2: TreeNode
        :rtype: TreeNode
        """
        if t1 is None and t2 is None:
            return
        if t1 is None:
            return t2
        if t2 is None:
            return t1
        t1.val += t2.val
        t1.right = self.mergeTrees(t1.right, t2.right)
        t1.left = self.mergeTrees(t1.left, t2.left)
        return t1

总结

此题做时没有理解这个TreeNode类是怎么用的,看了答案才明白。
后来尝试了:

t1.right.val
>> 2
t1.left.left.val
>> 5

该答案应该是广度优先的迭代方法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值