Lowest Common Ancestor in Binary Tree
The problem:
Given node P and node Q in a binary tree T.
Find out the lowest common ancestor of the two nodes.
Analysis:
The answer of this problem could only be the following two cases:
case 1: P or Q itself is the lowest common ancestor.
P
.........
X Q
case 2: P and Q are in the different sub-trees of a node.
A
..........
P Q
Additional Condition:
1. If the nodes in the tree has the parent pointer.
solution 1: Starting from node P and Q, traverse along the parent link back to the root, compute the distance of P to root and Q to root respectively.
Compute the difference d of those two distances. Move the node with longer distance d nodes along parent link. Then begin move P and Q one node each time back to root, and check the nodes of P and Q point to, if the nodes are the same node, return the node.
private TreeNode find_CLA(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return null;
if (p == null && q != null)
return q;
if (p != null && q == null)
return p;
int dist_p, dist_q, dist_diff;
TreeNode temp;
temp = p;
while (temp != root) {
temp = temp.parent;
dist_p++;
}
temp = q;
while (temp != root) {
temp = temp.parent;
dist_q++;
}
if (dist_p > dist_q) {
dist_diff = dist_p - dist_q;
temp = p;
}else {
dist_diff = dist_q - dist_p;
temp = q;
}
while (dist_diff > 0) {
temp = temp.parent;
dist_diff--;
}
while (p != root) {
if (p == q)
return p;
p = p.parent;
q = p.parent;
}
return root;
}
Solution 2. Use a Hashset.
The basic idea underlying this method is to use a hashset to record all nodes from P to root. then starting fom q to root, we check each node along this path. if the node appear in the hashset, then the node is the lowest common ancestor.
private TreeNode find_LCA(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return null;
if (p == null || q != null)
return q;
if (p != null || q == null)
return p;
Set<TreeNode> hashset = new HashSet<TreeNode> ();
while (p != root) {
hashset.add(p);
p = p.parent;
}
while (q != root) {
if (hashset.contains(p)){
return p;
}
}
return root;
}
What if we don't have parent pointer?
The problem gets complicated because we need to search all possible branches. But the idea behind it is also very elegant : use recursion!!!
The basic idea:
Since the problem is to find the lowest common ancestor, at each node, we would not be able to know its children in just one time traversaL.
Thus we choose to search through bottom-up way. Bottom-up way could be easily achieved through post-order traversal.
The invariant in recursion: (at each node)
Key idea: Once we encouter p or q, we return its pointer. Only LCA could be possible to have two sub-child-functions (not null).
1. We check if the current node is P or Q. Iff true, we return current node, and stop searching along this branch.
2. If the current node is neither P or Q. We check it's two sub-child-functions.
2.1 Iff two sub-children-functions's return value is not null, then the current node must be the LCA, we return it directly.
2.2 Iff only one branch's return value is not null, return pass the branch's return value into the current node's pre level.
Note: The return value could be the LCA or just p or q's reference.
2.3. Iff both branch's return value is null, pass the null into pre level.
Key : the null pointer here is very important, it helps to indicate whether a branch contains target node or any node in {P, Q}
private TreeNode find_LCA(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return null;
if (root == p || root == q)
return root;
TreeNode left = find_LCA(root.left, p, q);
TreeNode right = find_LCA(root.right, p, q);
if (left && right)
return root;
return left ? left : right;
}
Lowest Common Ancestor in Binary Tree的更多相关文章
- 48. 二叉树两结点的最低共同父结点(3种变种情况)[Get lowest common ancestor of binary tree]
[题目] 输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点. 二叉树的结点定义如下: C++ Code 123456 struct BinaryTreeNode { int ...
- [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...
- [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- [LeetCode]Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- 数据结构与算法(1)支线任务4——Lowest Common Ancestor of a Binary Tree
题目如下:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ Given a binary tree, fin ...
- Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- leetcode 236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...
随机推荐
- cygwin下用mysql c api连接数据库详解
一.典型错误: 错误1: 命令: gcc -I /usr/include/mysql/ -L /lib/ -lmysqlclient main.c 错误: /tmp/ccT0KqUQ.o:main.c ...
- 动态添加子视图 UIView 的正确方法
很多时候哥比较喜欢用代码添加视图,特别是要同时加很多UIView时,而且跟 xib 比起来代码更容易管理,在多人的项目中代码不容易 conflict. 但小牛哥最近发现很多新人都不太清楚正确的使用方法 ...
- Elasticsearch .Net Client NEST 索引DataSet数据
NEST 索引DataSet数据,先序列化然后转成dynamic 类型进行索引: /// <summary> /// 索引dataset /// </summary> /// ...
- javascript高级培训课程(一)
执行上下文 可执行代码类型-- 执行上下文类型 全局代码-- 全局上下文 函数代码-- 函数上下文 eval代码 -- eval上下文 arguments 超出传入参数个数的index 与形参不 ...
- JAVA跑马灯实现1
<TextView android:layout_width="wrap_content" android:layout_height=" ...
- eclipse-自动注释
在eclipse中自动添加'注释'的快捷键是'Alt+Shift+J',可以在 MyEclipse中的 Java->Code Style->Code Template->Commen ...
- Kettle的集群排序 2——(基于Windows)
5.使用kettle集群模式对相关的数据进行排序 既然,基于Carte服务程序所搭建的集群已经在Spoon中设定好了, 可以首先,先来启动四个节点: "以管理员身份运行"打开 四个 ...
- Cookie技术详解
1. Cookie的特性 属性: 1> name: Cookie的名字 2> value: Cookie的值 3> path: 可选,Cookie的存储路径,默认情况下的存储路径时访 ...
- ScheduleThreadPoolExecutor源码分析(二)
DelayedWorkQueue: DelayedWorkQueue实现了BlockingQueue接口,因此其可以作为线程池的任务队列.BlockingQueue的主要属性有以下几个: privat ...
- 大规模字符串检索-压缩trie树
本文使用压缩trie树实现字符串检索的功能.首先将字符串通过编码转化为二进制串,随后将二进制串插入到trie树中,在插入过程中同时实现压缩的功能. 字符编码采用Huffman,但最终测试发现不采用Hu ...