1. 程式人生 > >Lowest Common Ancestor II

Lowest Common Ancestor II

you color class while param mon pub null ren

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