实际上,用树的后序遍历就可以了。当访问到所求的节点A时,如果这两个节点不在一条线上,则它们必定分别在A的左子树和右子树上,后序遍历到第一个满足这个条件的节点就是所要求的节点A。另外,还必须对这两个节点在一条线上的情况,做特殊处理。
代码:
static bool lca(Node *root, int va, int vb, Node *&result, Node* parrent)


{
// left/right 左/右子树是否含有要判断的两节点之一
bool left = false, right = false;
if (!result && root->left) left = lca(root->left,va,vb,result,root);
if (!result && root->right) right = lca(root->right,va,vb,result,root);
// mid 当前节点是否是要判断的两节点之一
bool mid = false;
if (root->data == va || root->data == vb) mid=true;

if (!result && int(left + right + mid) == 2)
{
if (mid) result = parrent;
else result = root;
}
return left | mid | right ;
}

Node *lca(Node *root,int va, int vb)


{
if (root == NULL) return NULL;
Node *result = NULL;
lca(root, va, vb,result, NULL);
return result;
}
