题目:
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
题目理解:
找二叉搜索树中两节点的最近公共祖先。
方法:
思路与下面这个链接差不多,
https://blog.csdn.net/weixin_40283816/article/details/91346023
但可以先判断p、q和root的位置关系,如果在一侧,则去一侧寻找即可,如果在两侧,则root即为所求。
代码:
# 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 root == None:
return root
if p.val < root.val > q.val: # 均在左子树
return self.lowestCommonAncestor(root.left, p, q)
if p.val > root.val < q.val: # 均在右子树
return self.lowestCommonAncestor(root.right, p, q)
return root # 在两侧,根结点即为所求
也可以采用非递归的方式:
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
while root:
if p.val < root.val > q.val: # 在左子树寻找,直到有个节点满足p、q在其两侧
root = root.left
elif p.val > root.val < q.val: # 在右子树寻找,直到有个节点满足p、q在其两侧
root = root.right
else:
return root # p、q在两侧,返回该节点