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. 二叉树两结点的最低共同父结点(3种变种情况)[Get lowest common ancestor of binary tree]

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

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

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

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

  5. 数据结构与算法(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 ...

  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. 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. 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. NSNotificationCenter消息机制的介绍

    转载自http://www.cnblogs.com/pengyingh/articles/2367374.html NSNotificationCenter的作用是专门提供程序中不同类之间的消息通讯而 ...

  2. (转载)Windows 7 Ultimate(旗舰版)SP1 32/64位官方原版下载(2011年5月12日更新版)

    MSDN于2011年5月12日,最新发布简体中文Windows 7 Ultimate 旗舰版 SP1 DVD镜像安装包,分32位和64位两个版本.最新发行代号分别是:677486(32位),67740 ...

  3. AS【常用插件】

    安装插件,Settings -->[Plugins]-->搜索-->点击install-->重启AS 禁用插件,右侧面板会显示出已经安装的插件列表,取消勾选即可禁用插件 AS插 ...

  4. jQuery作用

    jquery是前端里面比较总要的,是很强大的一个选择器. 表单: 1.$(":input") 查找所有的input元素 2.$("text")    匹配所有的 ...

  5. iBatis 的删除一条记录

    Student.xml 设置删除参数的类型,可以是一个对象的 <delete id="delStudent" parameterClass="int" & ...

  6. html input 文本框的一些操作(限制输入...)

    1.取消按钮按下时的虚线框 在input里添加属性值 hideFocus 或者 HideFocus=true 2.只读文本框内容 在input里添加属性值 readonly 3.防止退后清空的TEXT ...

  7. 关于XML(一)。

    关于XML 什么是XML? XML是可扩展标记语言.类似于HTML,XML的宗旨是旨在传输数据,而非显示数据.其标签没有预定义,您需要自行定义标签.XML具有自我描述性,是W3C的推荐标准. XML与 ...

  8. HTML5+移动APP(1)

    前言: 介绍使用html5+(nativejs)和mui开发移动app(包括Android和iOs) HBuilder h5+开发app的环境,是一个对eclipse做了深度定的IDE. 官网: ht ...

  9. Relative与Absolute组合使用

    小伙伴们学习了绝对定位的方法:使用position:absolute可以实现被设置元素相对于浏览器(body)设置定位以后, 大家有没有想过可不可以相对于其它元素进行定位呢?答案是肯定的,当然可以.使 ...

  10. IIS部署.NET项目的有关事项_2015.07.02

    今天在做项目中的关于发送邮件的一些功能.在部署服务的时候遇到了一些奇葩的问题,基本上是和IIS有关的问题. 首先,项目是基于.NET Framework4.0 版本的,由于本人用的是一台新配置好的机器 ...