最近公共祖先
题目
给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。注意事项
假设给出的两个节点都在树中存在样例
对于下面这棵二叉树
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7题解
分别在左右子树中递归查找两个节点,如果两个节点都位于左子树或右子树,则返回该递归过程中的root节点,反之根节点就是最近公共祖先。
/**
* 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) {
if (root == A || root == B)
{
return root;
}
if (root == null)
{
return null;
}
TreeNode left = lowestCommonAncestor(root.left,A,B);
TreeNode right = lowestCommonAncestor(root.right,A,B);
if (left == null)
{
return right;
}
if (right == null)
{
return left;
}
return root;
}
}
Last Update 2016.10.6