转自:Pavel's Blog

Now let's say we want to find the LCA for nodes 4 and 9, we will need to traverse the whole tree to compare each node so that we can locate the nodes. Now considering that we start the traversal with the left branch (pre-order traversal) - we have the worst case here with O(n) running time.
Traversing the tree we compare the current node with both of the nodes and if one of them match, it means that one is the LCA on the respective branch. Let's say after traversing the above tree in pre-order  the first node that matches our nodes is 9 (2, 7, 2, 6, 5, 11, 5, 9). So the first obvious thought is that the 4 must be a child of 9, since we're already on the right child of node 5 and the pre-order traversal looks at the node first, then the left child and lastly the right child. Then we note node 9 as the LCA and we don't have to look further anymore.
 
Let's use another case, say we're looking for the LCA of 7 and 9. The first node in our pre-order traversal (2, 7, 2, 6, 5, 11, 5, 9, 4) is 7. Now here we can say that the LCA for the left branch is 7 because again, if the second node is in the same branch, independently of where and how deep it will be in this branch, the LCA will still be 7; thus we don't have to look in this branch anymore. But we still did not look at the right branch, so we keep traversing in a pre-order manner, but now omitting the other nodes: 2, 7, 5, 9. Now we can say that the LCA for that branch is 9. We can also affirm that the LCA for the branch with the root in node 5 is also 9. And in the end we have our nodes both in separate branches, which means that the LCA is the root of those branches - node 2.
 
The algorithm looks as a modified version of a pre-order tree traversal :

 public static Node lowestCommonAncestor(Node root, Node a, Node b) {
if (root == null) {
return null;
} if (root.equals(a) || root.equals(b)) {
// if at least one matched, no need to continue
// this is the LCA for this root
return root;
} Node l = lowestCommonAncestor(root.left, a, b);
Node r = lowestCommonAncestor(root.right, a, b); if (l != null && r != null) {
return root; // nodes are each on a seaparate branch
} // either one node is on one branch,
// or none was found in any of the branches
return l != null ? l : r;
}

For the node used we will use the following class:

 public class Node {
public int data;
public Node right;
public Node left; public Node(int data) {
this.data = data;
}
}

这个问题再follow up一下,就是要找到shortest path in a binary tree between two nodes

 public class Solution {
public static List<Node> shortestPath(Node root, Node a, Node b) {
ArrayList<Node> path1 = new ArrayList<Node>();
ArrayList<Node> path2 = new ArrayList<Node>();
Node LCA = lowestCommonAncestor(root, a, b);
helper(LCA.left, a, b, path1, new ArrayList<Node>());
helper(LCA.right, a, b, path2, new ArrayList<Node>());
Collections.reverse(path1);
path1.add(LCA);
path1.addAll(new ArrayList<Node>(path2));
return path1;
} public void helper(Node root, Node a, Node b, ArrayList<Node> outpath, ArrayList<Node> temp) {
if (root == null) return;
temp.add(root);
if (root == a || root == b) {
outpath = new ArrayList<Node>(temp);
return;
}
helper(root.left, a, b, outpath, temp);
helper(root.right, a, b, outpath, temp);
temp.remove(temp.size()-1);
}
}

别人的Stack做法,未深究 他说First stack is not really needed, a simple list would do - I just like symmetry.

 public static <V> void shortestpath(
Node<V> root, Node<V> a, Node<V> b,
Stack<Node<V>> outputPath) {
if (root == null) {
return;
}
if (root.data.equals(a.data) || root.data.equals(b.data)) {
outputPath.push(root);
return;
} shortestpath(root.left, a, b, outputPath);
shortestpath(root.right, a, b, outputPath); outputPath.push(root);
} public static List<Node> shortestPath(Node root, Node a, Node b) {
Stack<Node> path1 = new Stack<>();
Stack<Node> path2 = new Stack<>(); Node lca = lowestCommonAncestor(root, a, b); // This is to handle the case where one of the nodes IS the LCA
Node r = lca.equals(a) ? a : (lca.equals(b) ? b : lca); shortestpath(r.left, a, b, path1);
shortestpath(r.right, a, b, path2); path1.push(r);
// invert the second path
while (!path2.isEmpty()) {
path1.push(path2.pop());
}
return path1;
}

Summary: Lowest Common Ancestor in a Binary Tree & Shortest Path In a Binary Tree的更多相关文章

  1. Range Minimum Query and Lowest Common Ancestor

    作者:danielp 出处:http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=lowestCommonAnc ...

  2. A1143. Lowest Common Ancestor

    The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...

  3. PAT A1143 Lowest Common Ancestor (30 分)——二叉搜索树,lca

    The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...

  4. 1143 Lowest Common Ancestor

    The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...

  5. PAT 甲级 1143 Lowest Common Ancestor

    https://pintia.cn/problem-sets/994805342720868352/problems/994805343727501312 The lowest common ance ...

  6. PAT 1143 Lowest Common Ancestor[难][BST性质]

    1143 Lowest Common Ancestor(30 分) The lowest common ancestor (LCA) of two nodes U and V in a tree is ...

  7. [PAT] 1143 Lowest Common Ancestor(30 分)

    1143 Lowest Common Ancestor(30 分)The lowest common ancestor (LCA) of two nodes U and V in a tree is ...

  8. 1143. Lowest Common Ancestor (30)

    The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...

  9. PAT 1143 Lowest Common Ancestor

    The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...

随机推荐

  1. 整理一系列优秀的Android开发源码

    转:http://www.cnblogs.com/feifei1010/archive/2012/09/12/2681527.html 游戏类: 一.15个Android游戏源码(是以andengin ...

  2. Android 本地tomcat服务器接收处理手机上传的数据之案例演示

    上一篇:Android 本地tomcat服务器接收处理手机上传的数据之环境搭建     本篇基于上一篇搭建的服务器端环境,具体介绍Android真机上传数据到tomcat服务器的交互过程   场景:A ...

  3. 使用virtualbox 配置 linux host-only虚拟主机连接外网(转载)

    host-only 下的虚拟机之间可以互相访问,虚拟机和宿主机可以互相访问,但是虚拟机不能访问外网. 需要设置: 1.宿主机设置 先对宿主机(windows机器,我这里是win7系统)进行相关配置. ...

  4. wireshark和RawCap跟踪并解决中文乱码问题

    一.问题概述 说下程序的架构. 有个后台管理系统A,在页面修改数据后,会用httpClient发http请求给系统B: 系统B做了异步机制,收到A发的请求后,将数据封装为Mq消息发给RabbitMq, ...

  5. 为Docker容器中运行的gitlab添加ssh的一些问题记录

    最近做的一个东西,是将gitlab10.x的汉化版本,从源码编译(在源码中自己定制一些东西),然后制作成Docker镜像,作为Docker容器来运行 在启用容器中的gitlab的ssh的时候,遇到了一 ...

  6. C# 读取xml时,遇到xmlns的问题

    1.读取xml的时候,由于xml里有xmlns的属性,导致了读xml无法正常读取.通过网上搜索,发现需要先注册命名空间.  xmlns是XML Namespaces的缩写,中文名称是XML(标准通用标 ...

  7. 检查mono兼容性的工具MOAM

    mono的迁移工具,可以帮助我们从windows平台迁移到Linux平台,可以用来检测特定的.net的dll或exe程序对mono的兼容性,并能够给出不兼容的方法 项目地址 MoMA 项目介绍 MoM ...

  8. 【CF908G】New Year and Original Order 数位DP

    [CF908G]New Year and Original Order 题意:令S(i)表示将i中所有数位上的数拿出来,从小到大排序后组成一个新的数的值.如S(50394)=3459.求$\sum\l ...

  9. JPEG图片扩展信息读取与修改

    extends:http://www.2cto.com/kf/201405/303813.html 读写均是键值对的方式,需要注意的是值的类型需要严格按照api定义格式. 支持读写节点为: 1.TAG ...

  10. spring boot 通过Maven + tomcat 自动化部署

    使用maven创建的springboot项目,默认是jar包,springboot还有自己带的tomcat. 现在为了简单实现本地自动发布项目到服务器,需要通过发布war包的形式,通过maven将项目 ...