Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
Solution
public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode result;
if (root == null)
return null;
if (p == null && q == null) {
return root;
}
if (p == null) {
return q;
}
if (q == null) {
return p;
}
if (isReach(root, p) && isReach(root, q) && (!isReach(root.left, p) || !isReach(root.left, q))
&& (!isReach(root.right, p) || !isReach(root.right, q))) {
return root;
}
if (isReach(root.left, p) && isReach(root.left, q)) {
return lowestCommonAncestor(root.left, p, q);
} else {
return lowestCommonAncestor(root.right, p, q);
}
}
public static boolean isReach(TreeNode root, TreeNode p) {
if (root == null) {
return false;
}
if (root == p) {
return true;
} else {
return isReach(root.left, p) || isReach(root.right, p);
}
}
反思
这道题想了很久, 自己独立做出来收获很大
思路 先建立了一个isReach的函数
确定一下什么样的节点是LowestCommonAncestor
它有这样的性质 :
它可以reach节点p和节点q, 但它的left节点不可同时reach节点p和q 或者 right节点不能同时reach节点p和q
BST(Binary Search Tree) 二叉查找树
左子树上所有结点的值均小于它的根结点的值
右子树上所有结点的值均大于它的根结点的值
左、右子树也分别为二叉查找树
其他方法
上面的代码通用所有的树
注意到本题是BST, 其实可以通过比较值来确定isReach
如果 p 和 q 分别位于 root 的左右树, 这时候LCA就是root
因为root的左树无法reach 节点 q
下面再考虑 p 和 q 都位于 root 左子树的情况
以及 p 和 q 都位于 root 右子树的情况
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode result;
if (root == null)
return null;
if (p == null && q == null) {
return root;
}
if (p == null) {
return q;
}
if (q == null) {
return p;
}
if (Math.max(p.val, q.val) < root.val) {
return lowestCommonAncestor(root.left, p, q);
}
if (Math.min(p.val, q.val) > root.val) {
return lowestCommonAncestor(root.right, p, q);
}
return root;
// if (isReach(root, p) && isReach(root, q) && (!isReach(root.left, p)
// || !isReach(root.left, q))
// && (!isReach(root.right, p) || !isReach(root.right, q))) {
// return root;
// }
//
// if (isReach(root.left, p) && isReach(root.left, q)) {
// return lowestCommonAncestor(root.left, p, q);
// } else {
// return lowestCommonAncestor(root.right, p, q);
// }
}
}
Note
竟然发现这种代码的runtimes 远大于我自己的第一种方法果然性能不是自己推断的, 还是要实践才好