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).”
For example, the lowest common ancestor (LCA) of nodes
链接: http://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
一刷,思想是判断当前节点的值
1.与输入的两值之一相等,查找另一值是否在树里,是则当前值是LCA,否则返回None
2.当前值在两值中间,查找输入两值是否在树里,都在则返回当前值,否则返回None
3.当前值比最小值小或比最大值大,更新当前值
问题,若输入查找的值是None,输出None还是另外一值呢?
如果没有找到node可以返回另一个的话,二刷可以试一下recursive解法。
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
2and
8is
6. Another example is LCA of nodes
2and
4is
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解法。
相关文章推荐
- Swift编程规范之 Code Formatting
- openlayers2渐变色渲染
- openlayers2渐变色渲染
- Remove Duplicate Letters
- 机器学习
- Ugly Number
- Shortest Distance from All Buildings
- Asp.Net Core 发布和部署( MacOS + Linux + Nginx )
- (4) 百度2011研发工程师笔试卷
- SQL Server 存储过程
- 226. Invert Binary Tree
- PL/SQL Developer如何连接64位的Oracle图解
- SQL 触发器的作用,好处和坏处
- House Robber
- Windows驱动开发之驱动开发环境搭建
- SQL中declare申明变量
- SQL中declare申明变量
- html5调用摄像头拍照
- hive的查询注意事项以及优化总结 .
- SQL中的left outer join,inner join,right outer join用法