Java中递归最低的共同祖先

时间:2016-05-08 12:35:11

标签: java

我已经找到了leetcode中java中最低共同祖先问题的解决方案。另一个问题是,找到p和q的最低共同祖先,BST以root为根。 这是我的代码。

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        return left != null && right != null ? root : left == null?right :left;

    }

虽然这适用于大多数情况,但如果树是这样的,并且问题是最低的CommonAncestor(1,2,3)或最低共同的祖先2和3,其中root == 1;

1 -> 2 -> 3

那么在我看来这个解决方案将提供的答案是2, 这是因为在递归之后

left = null
right = 2

而实际答案是1。

然而这个解决方案有效。有人可以帮我理解我在这里遇到的错误。

2 个答案:

答案 0 :(得分:1)

遵循逻辑:

lowestCommonAncestor(root=1, p=2, q=3):
    if (root == null || root == p || root == q) return root;
    //     false           false        false

    left = lowestCommonAncestor(2, 2, 3):
               if (root == null || root == p || root == q) return root
               //     false            true                return 2

    right = lowestCommonAncestor(null, 2, 3):
                if (root == null || root == p || root == q) return root;
                //      true                                return null

    return left != null && right != null ? root : left == null ? right : left;
    //         true        false                     false             : 2

结果:2

遵循代码的最简单方法是使用调试器

答案 1 :(得分:1)

执行TreeNode right = lowestCommonAncestor(root.right, p, q);后,

你得到:

left=null;
right=2;

最后,结果= (left!=null && right!=null)?root:(left==null?right:left);

返回结果:2

相关问题