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

 

posted on 2017-06-07 05:45  codingEskimo  阅读(137)  评论(0编辑  收藏  举报

导航