Lowest Common Ancestor III

Posted codingEskimo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lowest Common Ancestor III相关的知识,希望对你有一定的参考价值。

Note:

This is question is very similar to LCA original. The only difference is that the node may not exist. So if the node is not exsit, of course the result will be null. So in order to check the exisitance, we need to use resultType. In the previous question, when we found null/A/B, we can return root. But here, we first need to process the null. Then we need to do the divide. After that, we will verify whether that node is A/B, because we need to determine the existance of A/B. 

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root The root of the binary tree.
     * @param A and B two nodes
     * @return: Return the LCA of the two nodes.
     */
    private class ResultType {
        TreeNode node;
        boolean isAExist;
        boolean isBExist;
        public ResultType(TreeNode node, boolean isAExist, boolean isBExist) {
            this.node = node;
            this.isAExist = isAExist;
            this.isBExist = isBExist;
        }
    }
    public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) {
        // write your code here
        ResultType node = findLCA(root, A, B);
        if (node.isAExist && node.isBExist) {
            return node.node;
        }
        return null;
    }
    private ResultType findLCA(TreeNode root, TreeNode A, TreeNode B) {
        if (root == null) {
            return new ResultType(null, false, false);
        }

        ResultType left = findLCA(root.left, A, B);
        ResultType right = findLCA(root.right, A, B);

        boolean isAExist = left.isAExist || right.isAExist || root == A;
        boolean isBExist = left.isBExist || right.isBExist || root == B;
        
        if (root == A || root == B) {
            return new ResultType(root, isAExist, isBExist);
        }

        if (left.node != null && right.node != null) {
            return new ResultType(root, isAExist, isBExist);
        }

        if (left.node != null) {
            return new ResultType(left.node, isAExist, isBExist);
        }

        if (right.node != null) {
            return new ResultType(right.node, isAExist, isBExist);
        }

        return new ResultType(null, isAExist, isBExist);
    }
}

 

以上是关于Lowest Common Ancestor III的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 236. Lowest Common Ancestor of a Binary Tree; 235. Lowest Common Ancestor of a Binary Searc

1143 Lowest Common Ancestor

1143 Lowest Common Ancestor

1143. Lowest Common Ancestor (30)

Lowest Common Ancestor III

A1143. Lowest Common Ancestor