我在leetcode中找到了java中最常见的祖先问题的解决方案。否则的问题是,找到p和q的最低公共祖先,BST根在根上。这是我的密码。
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;
}
虽然这适用于大多数情况,但如果树是这样的,并且问题是lowestCommonAncestor(1,2,3)或2和3的最低公共祖先,其中根==1;
1 -> 2 -> 3
那么在我看来,该解决方案将提供的答案是CCD_,这是因为在递归之后
left = null
right = 2
而实际答案是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
遵循代码的最简单方法是使用调试器。
执行TreeNode right = lowestCommonAncestor(root.right, p, q);
后,
你得到:
left=null;
right=2;
最后,结果为(left!=null && right!=null)?root:(left==null?right:left)
;
返回结果:2