public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
// 借助这个成员变量保存最近公共祖先.
private TreeNode lca = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
findNode(root, p, q);
return lca;
}
// [约定] 如果在 root 中能够找到 p 或者 q, 返回 true, 否则返回 false
private boolean findNode(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return false;
}
// 采取后序遍历的形式进行查找
int left = findNode(root.left, p, q) ? 1 : 0;
int right = findNode(root.right, p, q) ? 1 : 0;
// 访问根节点.
int mid = (root == p || root == q) ? 1 : 0;
// 接下来的操作非常神奇, 大家一定看好了~~~
if (left + right + mid == 2) {
lca = root;
}
// if ((left == 1 && right == 1 && mid == 0)
// || (left == 1 && right == 0 && mid == 1)
// || (left == 0 && right == 1 && mid == 1)) {
// lca = root;
// }
return (left + right + mid) > 0;
}
天才一行
if (left + right + mid == 2) {
lca = root;
}