码迷,mamicode.com
首页 > 其他好文 > 详细

Lowest Common Ancestor II

时间:2017-06-06 12:00:11      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:lca   nbsp   开始   and   class   param   arraylist   init   tco   

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

标签:lca   nbsp   开始   and   class   param   arraylist   init   tco   

原文地址:http://www.cnblogs.com/codingEskimo/p/6950626.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!