题目链接
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
题目原文
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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______
/ \
__2__ __8__
/ \ / \
0 _4_ 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
题目翻译
思路方法
思路一
根据二叉搜索树的性质,对于树中从root开始的节点:
如果p和q的值如果都小于root的值,那么它们的最低公共祖先一定在root的左子树;如果p和q的值如果都大于root的值,那么它们的最低公共祖先一定在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
"""
pointer = root
while pointer:
if p.val > pointer.val and q.val > pointer.val:
pointer = pointer.right
elif p.val < pointer.val and q.val < pointer.val:
pointer = pointer.left
else:
return pointer
思路二
类似前面的思路,不过是用递归实现。
代码
# 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
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)
else:
return root
思路三
更通用的做法是,先分别找到从根节点到两个节点的路径,根据这两个路径找最低公共祖先。方便的是,对于二叉搜索数,不需要BFS或DFS遍历节点找路径。
代码
# 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
"""
pathp = self.findPath(root, p)
pathq = self.findPath(root, q)
res = root
for i in xrange(1, min(len(pathp), len(pathq))):
if pathp[i] == pathq[i]:
res = pathp[i]
return res
def findPath(self, root, p):
path = []
while root.val != p.val:
path.append(root)
if p.val > root.val:
root = root.right
elif p.val < root.val:
root = root.left
path.append(p)
return path
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51498796