leetcode 231\235\236

231 2的幂

# method 1
 class Solution:
     def isPowerOfTwo(self, n: int) -> bool:
         if n == 0:
             return False
         while n%2 == 0:
             n /= 2
         return n==1


# method 2 位运算
# 若该数为2的幂次方,则该数的二进制只有一个1,后面都是0,例如000100,000010,所以利用x&(-x)可以保留最右边的一位1
 class Solution:
     def isPowerOfTwo(self, n: int) -> bool:
         if n == 0:
             return False
         return n & (-n) == n

# n&(n-1)去掉最右边的1
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n>0 and n&(n-1) == 0

235 二叉搜索树的最近公共祖先

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        while (root.val - p.val) * (root.val - q.val )>0:
            if root.val - p.val > 0:
                root = root.left
            else:
                root = root.right
        return root


class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root :return None
        p_path = self.getPath(root,p)
        q_path = self.getPath(root,q)

        p_len = len(p_path)
        q_len = len(q_path)
        min_len = min(p_len, q_len)
        for i in range(min_len):
            if p_path[i] == q_path[i]:
                max_index = i
                continue

        return p_path[max_index]


    def getPath(self,root, node):
        node_path = [root]
        while root != node:
            if root.val < node.val:
                root = root.right
                node_path.append(root)
            if root.val > node.val:
                root = root.left
                node_path.append(root)
        return node_path

236 二叉树的最近公共祖先

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#  遇到空值或p或q ,就返回
#  在root.left里面找
#  在root.right里面找
#  如果left里面找到了,right里面没找到,就返回left
#  如果right里面找到了,left里面没找到,就返回right
#  如果left 和 right都找到了,就返回他们的root
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if (not root) or (root == q) or (root == p):
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)

        if not left and not right: return None
        if not left: return right
        if not right: return left
        if left and right: return root
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值