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

//在二叉树中找出和为某一值的所有路径
#include <iostream>
#include <vector>
using namespace std;

//树结构
struct BTreeNode
{
	int m_nValue;
	BTreeNode *m_pLeft;
	BTreeNode *m_pRight;
}*BiTree;

//按照先序创建二叉树,0表示空
BTreeNode *CreateByPreOrder()
{
    int ch;
    cin>> ch;
    if(ch == 0)
    {
         return NULL;
    }
    else
    {
         BTreeNode *root = new BTreeNode();
		 root->m_nValue = ch;
		 root->m_pLeft = CreateByPreOrder();
		 root->m_pRight = CreateByPreOrder();
         return root;
    }
}

//按照先序打印树
void PrintBTByPreOrder(BTreeNode *root)
{
	if(!root)
	{
		return;
	}
	cout << root->m_nValue <<" ";
	PrintBTByPreOrder(root->m_pLeft);
	PrintBTByPreOrder(root->m_pRight);
}

//按照先序递归查找路径
void FindPathByPreOrder(BTreeNode *pTreeNode,int expectedSum,vector<int> &path,int currentSum)
{
	if(!pTreeNode)
	{
		return;
	}

	//累加到和里
	currentSum += pTreeNode->m_nValue;
	//将该节点的数据域入栈
	path.push_back(pTreeNode->m_nValue);

	bool isLeaf = (!pTreeNode->m_pLeft && !pTreeNode->m_pRight);
	//若当前为叶子节点,并且和恰好达到,则输出
	if(currentSum == expectedSum && isLeaf)
	{
		for(vector<int>::iterator iter = path.begin(); iter != path.end(); ++iter)
		{
			cout << *iter << '\t';
		}
		cout << endl;
	}
	//若不是叶子节点,则或者有左孩子
	if(pTreeNode->m_pLeft)
	{
		FindPathByPreOrder(pTreeNode->m_pLeft,expectedSum,path,currentSum);
	}
	//或者有右孩子
	if(pTreeNode->m_pRight)
	{
		FindPathByPreOrder(pTreeNode->m_pRight,expectedSum,path,currentSum);
	}

	//检测完的节点值要从“栈”里清除掉
	currentSum -= pTreeNode->m_nValue;
	path.pop_back();
	return ;
}

void main()
{
	BTreeNode *root=NULL;
	cout << "按照先序创建二叉树,输入各节点值(0表示空):"<<endl;
	root = CreateByPreOrder();
	cout << "按照先序打印:"<<endl;
	PrintBTByPreOrder(root);
	vector<int> temp;
	int currentSum = 0;
	int expectedSum;
	cout <<endl<<"请输入期望的和:";
	cin >> expectedSum;
	cout << "满足条件的路径有:"<<endl;
	FindPathByPreOrder(root,expectedSum,temp,currentSum);

	system("pause");
}

你可能感兴趣的:(在二叉树中找出和为某一输入值的所有路径)