在尝试解决这个问题时,我在 Leetcode 上找到了这个解决方案:
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
Leetcode 上的每个人似乎都理所当然地认为这是如何工作的。但我不明白。这里发生了什么,这是使用什么算法来查找二叉树的 LCA?
public TreeNode lowestCommonAncestorBinaryTree(TreeNode root, TreeNode p, TreeNode q) {
if(root==null) {
return null;
}
if(root==p) {
return p;
}
if(root==q) {
return q;
}
TreeNode left = lowestCommonAncestorBinaryTree(root.left, p, q);
TreeNode right = lowestCommonAncestorBinaryTree(root.right, p, q);
if (left != null && right != null) {
return root;
}
if(left!=null && right==null) {
return left;
}
if(right!=null && left==null) {
return right;
}
return null;
}