コード例 #1
0
Node* CommonAncestor(Node* pRoot, int val1, int val2)
{
	if (nullptr == pRoot)
		return nullptr;

	if ( (val1 < pRoot->data) && (pRoot->data <= val2) )
		return pRoot;

	if (val1 > pRoot->data)
		CommonAncestor(pRoot->pRight, val1, val2);
	else if (val2 <= pRoot->data)
		CommonAncestor(pRoot->pLeft, val1, val2);
}
コード例 #2
0
ファイル: q47.c プロジェクト: seanxiao2net/InterviewLearning
Node* CommonAncestor(Node* root, Node* tar1, Node* tar2)
{
	int isLeft1, isLeft2;
	if (root == NULL) return NULL;

	if ((root == tar1)||(root == tar2)) return root;

	isLeft1 = isNodeIn(root->left, tar1);
	isLeft2 = isNodeIn(root->left, tar2);

	if (isLeft1 != isLeft2)
	{
		return root;
	}
	else if ((isLeft1)&&(isLeft2))
	{
		return CommonAncestor(root->left, tar1, tar2);
	}
	else
	{
		return CommonAncestor(root->right, tar1, tar2);
	}
}
コード例 #3
0
void main()
{
	BSTree oBSTree;

	oBSTree.Insert(100);
	oBSTree.Insert(50);
	oBSTree.Insert(150);
	oBSTree.Insert(25);
	oBSTree.Insert(75);
	oBSTree.Insert(125);
	oBSTree.Insert(175);
	oBSTree.Insert(110);

	Node* pTmp = CommonAncestor(oBSTree.pRoot, 110, 175);

	cout << pTmp->data << endl;

	pTmp = CommonAncestor_Book(oBSTree.pRoot, 110, 175);

	cout << pTmp->data << endl;
}