您的位置:首页 > 其它

235. Lowest Common Ancestor of a Binary Search Tree

2016-07-05 07:22 330 查看
题目:

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.

链接:  http://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

一刷,思想是判断当前节点的值

1.与输入的两值之一相等,查找另一值是否在树里,是则当前值是LCA,否则返回None

2.当前值在两值中间,查找输入两值是否在树里,都在则返回当前值,否则返回None

3.当前值比最小值小或比最大值大,更新当前值

问题,若输入查找的值是None,输出None还是另外一值呢?

class Solution(object):
@staticmethod
def find(root, p):
if not p:
return False
cur = root
while root:
if root.val == p.val:
return True
if root.val < p.val:
root = root.right
else:
root = root.left
return False

def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root:
return root
if not p or not q:
return None
small = p if p.val < q.val else q
large = p if p.val >= q.val else q

cur = root
while cur:
if cur.val == small.val:
return cur if Solution.find(cur, large) else None
if cur.val == large.val:
return cur if Solution.find(cur, small) else None
if small.val < cur.val < large.val:
if Solution.find(cur, small) and Solution.find(cur, large):
return cur
else:
return None
cur = cur.right if cur.val < small.val else cur.left
return None


如果没有找到node可以返回另一个的话,二刷可以试一下recursive解法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: