您的位置:首页 > 其它

在二元树中找出和为某一值的所有路径

2011-03-15 16:58 337 查看
4.在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ /
5 12
/ /
4 7
则打印出两条路径:10, 12和10, 5, 7。

二元树节点的数据结构定义为:

struct BSTree_Node
{
int nValue; // value of node
BSTree_Node *pLeft; // left child of node
BSTree_Node *pRight; // right child of node
};



// 打印根结点到叶子结点权值和等于给定值的路径
// pPathArray数组用于存放临时路径,index表示当前叶子结点值在路径数组中的索引
void CBinarySearchTree::PrintFixValuePath(BSTree_Node *pRootNode, int nValue, int *pPathArray, int arraySize, int index)
{
	// 参数有效性
	if (pRootNode == NULL)
	{
		return;
	}	

	// 当前结点是否叶子结点
	if (pRootNode->pRight==NULL && pRootNode->pLeft==NULL)
	{
		if (nValue == pRootNode->nValue)
		{
			// 打印根结点
			for (int j=0; j<index; j++)
			{
				printf("%d, ", pPathArray[j]);
			}
			printf("%d, Right Path/n", pRootNode->nValue);		
		}	
		return;
	}	

	// 增加结点到路径数组
	int nTmpIndex = index;
	if (pPathArray != NULL && index<arraySize)
	{
		pPathArray[nTmpIndex] = pRootNode->nValue;
		nTmpIndex += 1;
	}
	
	// 权值确定需要向下遍历
	if (nValue-pRootNode->nValue >= 0)
	{
		// 遍历左子树
		PrintFixValuePath(pRootNode->pLeft, nValue-pRootNode->nValue, pPathArray, arraySize, nTmpIndex);

		// 遍历右子树
		PrintFixValuePath(pRootNode->pRight, nValue-pRootNode->nValue, pPathArray, arraySize, nTmpIndex);
	}	
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: