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

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

题意

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

解题思路

  • 利用BST的性质,如果该结点小于给定的其中一个结点,并且大于另外一个给定的结点,那么则认为该点是两个结点的最近公共祖先;

实现

class Solution(object):
   def lowestCommonAncestor(self, root, p, q):
       """
      递归实现
      :type root: TreeNode
      :type p: TreeNode
      :type q: TreeNode
      :rtype: TreeNode
      """
       if p.val < root.val and q.val < root.val:
           return self.lowestCommonAncestor(root.left, p, q)
       elif p.val > root.val and q.val > root.val:
           return self.lowestCommonAncestor(root.right, p, q)
       return root
   
   def lowestCommonAncestor(self, root, p, q):
       """
      迭代实现
      :type root: TreeNode
      :type p: TreeNode
      :type q: TreeNode
      :rtype: TreeNode
      """
       while root:
           if p.val < root.val and q.val < root.val:
               root = root.left
           elif p.val > root.val and q.val > root.val:
               root = root.right
           else:
               return root

posted @ 2019-04-01 17:13  banananana  阅读(306)  评论(0编辑  收藏  举报