Lowest Common Ancestor II
Posted codingEskimo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lowest Common Ancestor II相关的知识,希望对你有一定的参考价值。
Note
这道题和一不同,给了一个Node向上回溯的可能,所以不需要recersive的找。因为之前的那个题不能回头,所以必须先到最下面(或者找的A和B)。这道题我们只需要把A和B的path记住就可以了,然后比较path中从root到A或者B,一直到开始不一样的时候停止,那个最后一个一样的就是LCA。
/** * Definition of ParentTreeNode: * * class ParentTreeNode { * public ParentTreeNode parent, left, right; * } */ public class Solution { /** * @param root: The root of the tree * @param A, B: Two node in the tree * @return: The lowest common ancestor of A and B */ public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root, ParentTreeNode A, ParentTreeNode B) { // Write your code here List<ParentTreeNode> pathA = findPath2Root(A); List<ParentTreeNode> pathB = findPath2Root(B); int indexA = pathA.size() - 1; int indexB = pathB.size() - 1; ParentTreeNode rst = null; while (indexA >= 0 && indexB >= 0) { if (pathA.get(indexA) != pathB.get(indexB)) { break; } rst = pathA.get(indexA); indexA--; indexB--; } return rst; } private List<ParentTreeNode> findPath2Root(ParentTreeNode node) { List<ParentTreeNode> path = new ArrayList<ParentTreeNode>(); while (node != null) { path.add(node); node = node.parent; } return path; } }
以上是关于Lowest Common Ancestor II的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Searc