Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.

The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.

Example

    /     \

          /     \

For  and , the LCA is .

For  and , the LCA is .

For  and , the LCA is .

更复杂的参考:http://www.cnblogs.com/EdwardLiu/p/4265448.html

 public class Solution {
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
// write your code here
if (root == null) return null;
if (root==A || root==B) return root;
TreeNode lch = lowestCommonAncestor(root.left, A, B);
TreeNode rch = lowestCommonAncestor(root.right, A, B);
if (lch!=null && rch!=null) return root;
return lch==null? rch : lch;
}
}

最新文章

  1. mac 多php版本安装
  2. [翻译] AKKA笔记- ACTORSYSTEM (配置CONFIGURATION 与调度SCHEDULING) - 4(一)
  3. 解决python字典结构内存暴涨问题
  4. 项目实例——多表关联查询判断A的字段是否在B中,在显示该字段值,不在显示空;B的字段是否在C中,在显示该字段值,不在显示空。
  5. 三、jQuery--jQuery基础--jQuery基础课程--第1章 初识jQuery
  6. XML 解析器
  7. js控制html元素的readonly属性
  8. android学习笔记36——使用原始XML文件
  9. Python Opearte MS-SQL Use Pymssql
  10. (转)文件系统缓存dirty_ratio与dirty_background_ratio两个参数区别
  11. Jquery获得控件值的方法
  12. PHP面向对象之旅:抽象类继承抽象类(转)
  13. Cloudra公司CCP:DS——认证数据专家
  14. 设置应用中出现NFC服务,去掉
  15. 关于C++的子类指针指向父类
  16. 【转】关于python中re模块split方法的使用
  17. 【整理】图解隐马尔可夫模型(HMM)
  18. Android 网络框架 Retrofit2
  19. 2017-9-7-Linux Mint TFTP服务安装开启
  20. JavaScript String 对象常用方法

热门文章

  1. 如何清除 DBA_DATAPUMP_JOBS 视图中的异常数据泵作业
  2. Unix/Linux 查看文件大小
  3. Ant的Manifest任务
  4. 一、laya学习笔记 --- layabox环境搭建 HelloWorld(坑:ts版本问题解决方案)
  5. 关于nagios系统下使用shell脚本自定义监控插件的编写
  6. Android ActivityManager与WindowManager
  7. 阿里云服务器如何设置IPV6通过appstore的审核
  8. js---PC端滑动进度条
  9. ubuntu16.04下安装kdevelop和汉化
  10. MapReduce规约