求二叉树的最小公共祖先(lowest common ancestor),如果是BST比较简单,时间复杂度O(logN),如果是普通二叉树稍微复杂一些,时间复杂度O(N);代码如下
public class Solution {
/*
* 如果是BST的情况
*/
public static TreeNode getBSTLCA(TreeNode root, TreeNode p, TreeNode q) {
if (p.value < root.value && q.value < root.value) {
return getBSTLCA(root.left, p, q);
} else if (p.value > root.value && q.value > root.value) {
return getBSTLCA(root.right, p, q);
} else {
return root;
}
}
/*
* 如果是普通二叉树的情况,查找p、q包含在哪个子树,如果某个root下找到了两个节点则为LCA
*/
public static TreeNode getLCA(TreeNode root, TreeNode p, TreeNode q) {
// 返回条件,节点为空或者找到了p或q
if (root == null || root == q || root == p) {
return root;
}
// 如果root没找到, 接着在root left和right 递归查找,返回查找值
TreeNode left = getLCA(root.left, p, q);
TreeNode right = getLCA(root.right, p, q);
// 如果left和right都找到了,则root为LCA
if (left != null && right != null) {
return root;
}
// 哪边找到了返回哪边,都没找到 返回null
return left != null ? left : right;
}
/*
* 如果节点带了父指针,则为两个链表查找LCA,问题变简单了
*/
}