Leetcode 235 Lowest Common Ancestor of a Binary Search Tree
2015-07-11 09:40
399 查看
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
BST,从root处开始,满足公共root的node必为满足值介于两者之间的第一个值
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.
BST,从root处开始,满足公共root的node必为满足值介于两者之间的第一个值
class Solution: # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): while 1: if root.val > max(p.val,q.val): root = root.left elif root.val < min(p.val,q.val): root = root.right else: return root
相关文章推荐
- 【JSP】背景图片自适应
- JS正则表达式验证手机号、电话和邮箱
- recv 和 send 函数分析
- javascript中JSON对象与JSON字符串相互转换实例
- android开发设置图片透明度的2种方法
- (2)cocos2dx在windows环境下中文显示乱码
- android使用广播退出应用程序
- 让人纠结不方便的便捷支付
- ajax的学习
- bzoj-1492 货币兑换Cash (1)——平衡树维护凸包
- linux 下一个 osw先从操作系统和标准脚本主动发起
- python面向对象的继承
- PHP:冒泡排序法
- 简析TCP协议的TIME_WAIT与CLOSE_WAIT状态
- C/C++ extern practices
- 【DRP】删除递归树的操作
- css中display属性
- linux下mysql的root密码忘记解决方法
- 篮球游戏AI预研
- mysql centos7安装