474.最近公共祖先II

描述

给一棵二叉树和二叉树中的两个节点,找到这两个节点的最近公共祖先 LCA。两个节点的最近公共祖先,是指两个节点的所有父亲节点中(包括这两个节点),离这两个节点最近的公共的节点。每个节点除了左右儿子指针以外,还包含一个父亲指针parent,指向自己的父亲。

样例

对于下面的这棵二叉树

          4
         / \
        3   7
           / \
          5   6
    LCA(3, 5) = 4
    LCA(5, 6) = 7
    LCA(6, 7) = 7

代码

/**
 * 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) {
        // 用数组分别存储 A , B 结点向上寻找的结点
        ArrayList pathA = getPath2Root(A);
        ArrayList pathB = getPath2Root(B);
        
        // 忘记 -1 会出现数组下标越界
        int indexA = pathA.size() - 1;
        int indexB = pathB.size() - 1;
        
        ParentTreeNode lowestAncestor = null;
        // 从最远的公共祖先开始寻找,找到最近的公共祖先
        while (indexA >= 0 && indexB >= 0) {
            // break 时不需要更新 lowestAncestor,
            // 其上一个 pathA.get(indexA) == pathB.get(indexB) 的 lowestAncestor 是所需的
            if (pathA.get(indexA) != pathB.get(indexB)) {
                break;
            }
            lowestAncestor = pathA.get(indexA);
            indexA--;
            indexB--;
        }
        
        return lowestAncestor;
    }
    
    private ArrayList getPath2Root(ParentTreeNode node) {
        ArrayList path = new ArrayList<>();
        while (node != null) {
            path.add(node);
            node = node.parent;
        }
        return path;
    }

你可能感兴趣的:(474.最近公共祖先II)