Lowest Common Ancestor of a Binary Tree
来源:互联网 发布:湖南省网络交易监管网 编辑:程序博客网 时间:2024/05/16 19:54
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes
in the tree.
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another
example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself
according to the LCA definition.
也可以用递归来实现。
在root为根的二叉树中找A,B的LCA:
如果找到了就返回这个LCA
如果只碰到A,就返回A
如果只碰到B,就返回B
如果都没有,就返回null
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root==null||root==p||root==q)return root;TreeNode left=lowestCommonAncestor(root.left, p, q);TreeNode right=lowestCommonAncestor(root.right, p, q);if(left!=null&&right!=null)return root;if(left!=null)return left;if(right!=null)return right;return null;}
0 0
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree(***)
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Lowest Common Ancestor of a Binary Tree
- 分享一些不错的学习IOS资源网站
- 数据结构中排序方法基本概念 及 分类
- 黑马程序员——IDE&Object类、常用API-String类、常用API-Arrays、System、StringBuffer&Integer类和Date类、对象数组
- poj1734Sightseeing trip floyd最小环
- 汤姆猫实现代码
- Lowest Common Ancestor of a Binary Tree
- HDU 1542 Atlantis(线段树扫描线,面积并)
- Alex / OverFeat / VGG 中的卷积参数
- 三种东西永远不要放到数据库里
- mongoDB 3.0 安全权限访问控制
- Linux下如何查看系统启动时间和运行时间
- 深入理解开源数据库中间件 Vitess:核心特性以及如何进行数据存储的堆叠
- python 模块
- HDU 5412 CRB and Queries(区间第K大 树套树 按值建树)