

【解题思路】
如果节点c为目标节点之一,且c.left及其子树中包含另一个目标节点,那么c是最近公共祖先;
如果节点c为目标节点之一,且c.right及其子树中包含另一个目标节点,那么c是最近公共祖先;
如果c的左右子树中都包含目标节点,那么c是最近公共祖先。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode to1, to2;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode ans = root, c = root;
to1 = p; to2 = q;
while(c != null)
{
if((c==p || c==q) && find(c.left))
{
ans = c;
break;
}
else if((c==p || c==q) && find(c.right))
{
ans = c;
break;
}
else if(find(c.left) && find(c.right) )
{
ans = c;
break;
}
else if(find(c.left))
{
c = c.left;
}
else{
c = c.right;
}
}
return ans;
}
public boolean find(TreeNode c)
{
if(c == null) return false;
else if(c == to1 || c == to2) return true;
return find(c.left) || find(c.right);
}
}
本文介绍了一种寻找二叉树中两个指定节点的最近公共祖先的方法。通过递归搜索和节点比较,算法能有效确定目标节点的最近公共祖先。

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



