找出二叉树中的最低公共父节点(LCA)

enum
{
   FOUND_NONE;
   FOUND_ONE;
   FOUND_BOTH;
}
FOUND

Node *FindLCA(Node *pRoot, Node *p1, Node *p2)
{
	Node *pFound = NULL;
	findLCAImpl(pRoot, p1, p2, &pFound)
	
	return pFound;
}


FOUND findLCAImpl(Node *pRoot, Node *p1, Node *p2, Node ** ppFound)
{
    if (!pRoot)
	    return FOUND_NONE;
		
	FOUND find1 = findLCAImpl(pRoot->left, p1, p2, ppFound);
	if (find1 == FOUND_BOTH)
		return find1;
	
	FOUND find2 = findLCAImpl(pRoot->right, p1, p2, ppFound);
	if (find2 == FOUND_BOTH)
		return find2;
		
	if (find1 == FOUND_ONE && find2 == FOUND_ONE)
	{
		*ppFound = pRoot;
		return FOUND_BOTH;
	}
	
	if (find1 == FOUND_ONE || find2 == FOUND_ONE)
	{
		if (pRoot == p1 || pRoot == p2)
		{
			*ppFound = pRoot;
			return FOUND_BOTH;
		}
		else
		{
			return FOUND_ONE;
		}
	}
	
	if (pRoot == p1 || pRoot == p2)
		return FOUND_ONE;
		
	return FOUND_NONE;
}


你可能感兴趣的:(找出二叉树中的最低公共父节点(LCA))