自己动手“敲”微软100题系列四

题目如下:


注意要找的路径是到叶节点,我之前以为是到其中某个节点都行。

下面上代码:


//参考:http://www.cnblogs.com/caidaxia/archive/2011/10/14/2212369.html
//主要用了一个数组,类似于栈的结构去保存路径

#include <iostream>
#include <iomanip>
#define MAX_HEIGHT 10
using namespace std;

//二叉树结构体
struct BinaryTreeNode // a node in the binary tree
{
	int m_nValue; // value of node
	BinaryTreeNode *m_pLeft; // left child of node
	BinaryTreeNode *m_pRight; // right child of node
};


//建立二叉树
void buildBinTree(BinaryTreeNode *&root,int* chs) //
{
	static int inputCharIndex=0; //局部静态变量,用于遍历chs数组
	int ch;	
	ch=chs[inputCharIndex++];
	if (ch == NULL) //表示空节点
	{
		root=NULL;
	}else
	{
		root =new BinaryTreeNode; //必须开避空间
		root->m_pLeft= NULL;
		root->m_pRight= NULL;
		root->m_nValue=ch;
		buildBinTree(root->m_pLeft,chs);
		buildBinTree(root->m_pRight,chs);
	}
	
}

//前序遍历打印树    
void printfBSTree(BinaryTreeNode* root)
{

	if (NULL == root)
	{
		cout <<setfill(' ')<<setw(4)<<'#';
		return;
	}

	cout <<setfill(' ')<<setw(4)<<root->m_nValue;
	printfBSTree(root->m_pLeft);
	printfBSTree(root->m_pRight);
	return;	
}

//打印某条路径信息
void printPath(int path[],int top)
{
	for (int i=0;i<top;i++)
	{
		cout << setw(5) << setfill(' ')<< path[i];
	}
	cout << endl;
}

//参考了文档,迭代找路径
void helper(BinaryTreeNode * root, int sum, int path[], int top) {
	path[top++] = root->m_nValue;
	sum -= root->m_nValue;
	if (root->m_pLeft == NULL && root->m_pRight==NULL) {
		if (sum == 0) printPath(path, top);//一直到叶子节点为止
	} else {
		if (root->m_pLeft != NULL) helper(root->m_pLeft, sum, path, top);
		if (root->m_pRight!=NULL) helper(root->m_pRight, sum, path, top);
	}
	top --;
	sum += root->m_nValue;    //....
}

void printPaths(BinaryTreeNode * root, int sum) {
	int path[MAX_HEIGHT];
	helper(root, sum, path, 0);
}


void main()
{
	//按中序遍历构建树,空节点用NULL表示
	int chs[]={10,5,4,NULL,NULL,7,NULL,NULL,12,NULL,NULL};
	int sum=22;
	BinaryTreeNode* root;
	buildBinTree(root,chs); 

	cout << "前序遍历打印出树" << endl;
	printfBSTree(root);
	cout << endl << "和为 "<< sum << "有路径如下" << endl;
	printPaths(root,sum);
	//让控制台程序停留下	
	while(1);
}


下面是运行结果:

有什么问题,欢迎各位交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值