[LintCode]Lowest Common Ancestor
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
// 2015-3-23 DFS
if (A == null || B ==null) {
return null;
}
if (root == null || root == A || root == B) {
return root;
}
// divide
TreeNode left = lowestCommonAncestor(root.left, A, B);
TreeNode right = lowestCommonAncestor(root.right, A, B);
// conquer
if (left != null && right != null) {
return root;
} else if (left != null) {
return left;
} else if (right != null) {
return right;
} else {
return null;
}
}
}
本文介绍了一种寻找二叉搜索树中两个节点的最低公共祖先(LCA)的方法。通过递归深度优先搜索(DFS),该算法有效地解决了这一问题,并提供了完整的Java实现代码。
253

被折叠的 条评论
为什么被折叠?



