LeetCode腾讯精选练习50——第十五天

题目231:2的幂
给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
题解:

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        # 位运算
        # return n>0 and not (n & (n-1))
        return n>0 and ((1<<30)%n == 0)
        # 取对数
        # return n>0 and log2(n) == int(log2(n))

运行结果:
在这里插入图片描述
题目235:二叉搜索树的最近公共祖先
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
题解:

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        # 利用二叉树自身的性质
        if p.val < root.val and q.val < root.val:
            return self.lowestCommonAncestor(root.left, p, q)
        if p.val > root.val and q.val > root.val:
            return self.lowestCommonAncestor(root.right, p, q)
        return root

运行结果:
在这里插入图片描述
题目236:二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
题解:

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root in (None,p,q):
            return root
        
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        # return right if left==None else left if right==None else root
        if left and right:
            return root
        elif left:
            return left
        elif right:
            return right 

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44315884/article/details/113134267