public static Node LCA(Node root, Node a, Node b){
Node left=null,right=null;
if(root==null)
{
return null;
}
// If the root is one of a or b, then it is the LCA
if(root==a || root==b)
{
return root;
}
left=LCA(root.left,a,b);
right=LCA(root.right,a,b);
// If both nodes lie in left or right then their LCA is in left or right,
// Otherwise root is their LCA
if(left!=null && right!=null)
{
return root;
}
return (left!=null)? left: right;
}
本文介绍了一种在二叉树中查找两个节点最近公共祖先的算法,该算法利用递归方式实现,适用于不同场景下的应用。
2669

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



