task15,leetcode:231,235,236-python

231.2的幂

解法一:最朴素的方法,依次除二判断。如果一个数是2的幂,那么不断除2肯定会得到1。反正亦然,如果不能通过反复除二得到1,那么一定不是2的幂。

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        while n :
            if n < 1:					# 剪枝
                return False
            if n == 1:
                return True
            else:
                n /= 2
        return False

解法二:位运算
如果一个数是2的幂,那么其二进制有且仅有一位为1。因此使用与运算可轻易得到结果。

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n == 0:
            return False
        return n & (n - 1) == 0

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

此题的关键就是意识到,自顶向下遍历时,第一个val在要求的两个结点之间的结点就是最近公共祖先。

# 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':
        
        p, q = p.val, q.val
        if p > q:
            p, q = q, p

        node = root
        while node:
            if p <= node.val <= q:
                return node
            elif node.val < p:            # 根节点小于最小值,则肯定在右子树中
                node = node.right
            else:                         # 否则在左子树中
                node = node.left

时间复杂度O(n),空间复杂度O(1)

236.二叉树的最近公共祖先

虽然只比235少了一个条件,但是难度上升了好几个档次。
具体思路参考高star解析:后续遍历dfs

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root or root == p or root == q:
            # 如果root为空或者为p、q,向上返回root
            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                   # 右子树为空的时候,返回左子树
        return root                                 # 都非空的时候,返回root
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值