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

Lowest Common Ancestor III

时间:2017-06-07 09:58:15      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:find   node   isa   ini   code   roc   span   result   determine   

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

标签:find   node   isa   ini   code   roc   span   result   determine   

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

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