博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Lintcode: Lowest Common Ancestor
阅读量:7235 次
发布时间:2019-06-29

本文共 1020 字,大约阅读时间需要 3 分钟。

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        4    /     \  3         7          /     \        5         6For 3 and 5, the LCA is 4.For 5 and 6, the LCA is 7.For 6 and 7, the LCA is 7.

更复杂的参考:

1 public class Solution { 2     /** 3      * @param root: The root of the binary search tree. 4      * @param A and B: two nodes in a Binary. 5      * @return: Return the least common ancestor(LCA) of the two nodes. 6      */ 7     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) { 8         // write your code here 9         if (root == null) return null;10         if (root==A || root==B) return root;11         TreeNode lch = lowestCommonAncestor(root.left, A, B);12         TreeNode rch = lowestCommonAncestor(root.right, A, B);13         if (lch!=null && rch!=null) return root;14         return lch==null? rch : lch;15     }16 }

 

转载地址:http://ojgfm.baihongyu.com/

你可能感兴趣的文章
靠谱的 关闭Windows10自动更新
查看>>
Ocelot简易教程(二)之快速开始2
查看>>
Elide 4.3.1 发布,雅虎开源的应用数据 API 搭建平台
查看>>
[Docker]Docker镜像
查看>>
如何抓取WebClient、HttpWebRequest、WebRequest无法获取的网页源码,下面将为你解答...
查看>>
[HBase]HBase安装
查看>>
微服务 到底解决了什么问题?非用不可吗?
查看>>
基本概念
查看>>
【Web API系列教程】1.2 — Web API 2中的Action Results
查看>>
Memcached的扩容源码分析
查看>>
DOM操作之--元素的创建,添加,删除
查看>>
关于Vue.js和React.js,听听国外的开发者怎么说?
查看>>
4.variables
查看>>
2.sparkSQL--DataFrames与RDDs的相互转换
查看>>
鼠标放上超链接显示背景效果
查看>>
【小摘抄】关于C++11下 string各类用法(持续更新)
查看>>
淘宝Buy+九月上线测试,你说靠谱吗?
查看>>
erlang的函数
查看>>
Spring Boot入门(2)使用MySQL数据库
查看>>
支撑全网70%世界杯流量 盘点世界杯直播背后的阿里云黑科技
查看>>