Lettcode_235_Lowest Common Ancestor of a Binary Search Tree
2015-09-12 11:31
423 查看
本文是在学习中的总结,欢迎转载但请注明出处:/article/1495209.html
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
Another example is LCA of nodes
since a node can be a descendant of itself according to the LCA definition.
思路:
(1)题意为给定一个BST以及该树上两节点,求这两节点的最近公共祖先。
(2)该题比较简单,通过递归很好实现。如果两节点分别分布在根节点的左右子树上,那么它们的最近公共祖先只能是树根;如果两节点同时分部在根节点的相同子树上,则需要分别递归进行判定。
(3)详情见下方代码。希望本文对你有所帮助。
算法代码实现如下:
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.
思路:
(1)题意为给定一个BST以及该树上两节点,求这两节点的最近公共祖先。
(2)该题比较简单,通过递归很好实现。如果两节点分别分布在根节点的左右子树上,那么它们的最近公共祖先只能是树根;如果两节点同时分部在根节点的相同子树上,则需要分别递归进行判定。
(3)详情见下方代码。希望本文对你有所帮助。
算法代码实现如下:
package leetcode; import leetcode.utils.TreeNode; /** * * @author liqqc * */ public class Lowest_Common_Ancestor_of_a_Binary_Search_Tree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { // 在树的两边 if (p.val >= root.val && q.val <= root.val) return root; else if (p.val <= root.val && q.val >= root.val) return root; // 在树的一边 左边或右边 else if (p.val < root.val && q.val < root.val) { // 左边 return lowestCommonAncestor(root.left, p, q); } else { // 右边 return lowestCommonAncestor(root.right, p, q); } } }
相关文章推荐
- 数据结构实践——链表:多项式求和
- 上传图片 生成指定大小的缩略图
- php广告图片循环播放 幻灯片效果
- c++11——模板的细节改进
- C/C++中extern关键字详解
- MSTP+OSPF+VRRP综合实验指导书
- Spring初识(一)
- codeforces 377B Modulo Sum(数学,dp)
- ios ftp开发中的一个NSString问题
- ASP 生成缩略图
- IE以及其他浏览器主页被劫持到www.2345.com/?kunown的解决办法
- EQueue文件持久化消息关键点设计思路
- jquery ajax提交表单数据的两种方式
- Linux 下启动、关闭tomcat 杀掉进程等命令
- 关于 configure.in 文档中的若干笔记
- NS_ENUM & NS_OPTIONS 枚举
- 求两点间的距离
- CCF 201409-2 画图 题解
- SOAP的简单理解
- poj 1719 Shooting Contest