2021-01-27

231、2的幂

class Solution:

    def isPowerOfTwo(self, n: int) -> bool:

        return n > 0 and not (n & (n - 1))

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':

        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、二叉搜索树的最近公共祖先

# 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':

        if root is None:

            return root

        if root is p or root is q:

            return root


        left=self.lowestCommonAncestor(root.left,p,q)

        right=self.lowestCommonAncestor(root.right,p,q)

        if left and right:

            return root

        if left:

            return left

        if right:

            return right

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容