腾讯精选44--python

mac2022-06-30  93

# 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 lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if not root: return None aim=root pp=p.val qq=q.val if pp<qq: while aim.val!=pp and aim.val!=qq: a=aim.val if a>qq: aim=aim.left if a<pp: aim=aim.right if a>pp and a<qq: return aim else: while aim.val!=pp and aim.val!=qq: a=aim.val if a>pp: aim=aim.left if a<qq: aim=aim.right if a>qq and a<pp: return aim return aim

二叉搜索树的定义一定要搞明白,明白了以后就是比大小

最新回复(0)