Lowest Common Ancestor in Binary Tree

时间:2022-09-30 09:57:29

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的更多相关文章

  1. 48&period; 二叉树两结点的最低共同父结点&lpar;3种变种情况&rpar;&lbrack;Get lowest common ancestor of binary tree&rsqb;

    [题目] 输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点. 二叉树的结点定义如下:  C++ Code  123456   struct BinaryTreeNode {     int ...

  2. &lbrack;LeetCode&rsqb; 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 ...

  3. &lbrack;LeetCode&rsqb; 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 ...

  4. &lbrack;LeetCode&rsqb;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 ...

  5. 数据结构与算法&lpar;1&rpar;支线任务4——Lowest Common Ancestor of a Binary Tree

    题目如下:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ Given a binary tree, fin ...

  6. 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 ...

  7. 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 ...

  8. leetcode 235&period; 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 ...

  9. leetcode 236&period; 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 ...

随机推荐

  1. NVMe over Fabrics:概念、应用和实现

    对于大部分人来说,NVMe over Fabrics(简称NVMf)还是个新东西,因为其第一个正式版本的协议在今年6月份才发布.但是这并不影响人们对NVMf的关注,因为这项依托于NVMe的技术很可能继 ...

  2. Jade之条件语句

    条件语句 jade支持js中的if/elseif/else语法. jade: - var user = { description: 'foo bar baz' } - var authorised ...

  3. SQL Server访问MySql

    使用环境:操作系统:window7数据库:SQL Server2005.MySql5.01.在安装了SQL Server的服务器上安装MySql的ODBC驱动:下载链接:http://dev.mysq ...

  4. &lbrack;Git&rsqb; Github客户端上publish后一直转圈,web上未上传成功

    连续试了几次,publish后一直处于publish状态,点击其它repositories再点回来就没动静了,也看不到Sys按钮...最后发现,是要等很久才会成功,天朝的网络伤不起

  5. C&num;数字类型及运算符

  6. bzoj2730(矿场搭建)

    矿场搭建,不知道为什么,莫名其妙T了在212上,额,zyh数据真的坑. bzoj200轻松跑过啊. 就是点双联通分量缩点,然后标记割点,一个块如果有>=2个割点,则不需要挖矿洞, 如果只有一割点 ...

  7. 新手级配置 react react-router4&period;0 redux fetch sass

    前言 最近公司来了几个实习生,刚好我手头没什么要紧事,然后领导让我带他们学习react, 为下一个react项目做基础. 然后随手写了几个demo,帮助他们了解正经项目如何去构建配置项目. 现在分享出 ...

  8. windows防火墙实验-命令行设置远程桌面连接以及禁止浏览器上网

    windows防火墙实验-设置远程桌面连接以及禁止浏览器上网 实验环境: 1.win2008远程桌面服务 2.win7-1 10.10.10.136 3.win7-2 10.10.10.153 实验步 ...

  9. 三、html样式、链接、表格

  10. 我一直跑的分类LSTM模型原来是这一个,新闻分类网络

    原始的github可以参考这里: https://github.com/FudanNLP/nlpcc2017_news_headline_categorization 我的经验文章可以参考这里: ht ...