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

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

输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。
例如输入整数22 和如下二元树         
10       
/       
5  12    
/    
4 7
则打印出两条路径:10, 12 和10, 5, 7。

// 在二元树中找出和为某一值的所有路径.cpp : Defines the entry point for the console application.
//
/*
题目:在二元树中找出和为某一值的所有路径

输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。
例如输入整数22 和如下二元树          
10        
/        
5  12     
/     
4 7
则打印出两条路径:10, 12 和10, 5, 7。
*/

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <vector>
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
};

//BinaryTreeNode headNode = NULL;

void addBSTreeNode(BinaryTreeNode *& pCurrent,int data)
{
	if (pCurrent == NULL)
	{
		BinaryTreeNode *BSTreeNode = new BinaryTreeNode();
		BSTreeNode->m_pLeft = NULL;
		BSTreeNode->m_pRight = NULL;
		BSTreeNode->m_nValue = data;
		pCurrent = BSTreeNode;
	}else
	{
		if (pCurrent->m_nValue > data)
		{
			addBSTreeNode(pCurrent->m_pLeft,data);
		}else
		{
			addBSTreeNode(pCurrent->m_pRight,data);
		}
	}
}

void findPath(BinaryTreeNode *pCurrent,int sum,vector<int> path,int curSum)
{
	if (!pCurrent)
	{
		return;
	}
	curSum += pCurrent->m_nValue;
	path.push_back(pCurrent->m_nValue);
	bool isLeaf = !(pCurrent->m_pLeft) && !(pCurrent->m_pRight);
	if (curSum == sum && isLeaf)
	{
		vector<int>::iterator iter;
		for (iter = path.begin();iter != path.end();iter++)
		{
			cout << *iter << "	";
		}
		cout << endl;
	}
	if (pCurrent->m_pLeft)
	{
		findPath(pCurrent->m_pLeft,sum,path,curSum);
	}
	if (pCurrent->m_pRight)
	{
		findPath(pCurrent->m_pRight,sum,path,curSum);
	}
	curSum -= pCurrent->m_nValue;
	path.pop_back();
}
int _tmain(int argc, _TCHAR* argv[])
{
	BinaryTreeNode *BSNode = NULL;
	addBSTreeNode(BSNode,10);
	addBSTreeNode(BSNode,5);
	addBSTreeNode(BSNode,12);
	addBSTreeNode(BSNode,4);
	addBSTreeNode(BSNode,7);
	vector<int> path;
	int sum = 0;
	findPath(BSNode,22,path,sum);
		system("pause");
	return 0;
}

原文地址:https://www.cnblogs.com/study-programmer/p/3408760.html