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;
    } 
}

 

posted on 2017-06-06 11:27  codingEskimo  阅读(393)  评论(0编辑  收藏  举报

导航