题目如下:
解题思路:因为是BST,对于任意一个node,如果其val在p和q之间,那么说明p和q分别在其左子树和右子树,所以node就是其最低的祖父节点;如果val和q或者q相等,同样node就是其最低的祖父节点;如果p和q都比val大,说明这两个节点在node的右边,往右子树方向遍历;如果都小,往左子树方向遍历。
代码如下:
# 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 """ minv,maxv = min(p.val,q.val),max(p.val,q.val) if root.val == minv or root.val == maxv: return root elif root.val > minv and root.val < maxv: return root elif root.val < minv: return self.lowestCommonAncestor(root.right, p, q) else: return self.lowestCommonAncestor(root.left, p, q)