leetcode--python--剑指 Offer 68 - I.

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

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先

  1. 首先二叉搜索树是左节点值雄小于根节点小于右节点的值
  2. 如果某个节点是指定节点的最近公共祖先,那么有2中情况:1)根节点的值等于其中一个节点的值 2)根节点的值大于左节点的值小于右节点的值
# 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:
            if root.val > p.val and root.val > q.val:
                root = root.left
            elif root.val < p.val and root.val < q.val:
                root = root.right
            else:
                break
        return(root)

你可能感兴趣的:(leetcode-python)