题目:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径.从树的根结点开始往下一直到叶结点所经过的结点形成一条路径.
#include <vector>
#include <stdio.h>
using std::vector;
void FindPath(BinaryTreeNode* pRoot, int expectedSum, vector<int>& path,
int currentSum);
void FindPath(BinaryTreeNode* pRoot, int expectedSum)
{
if (pRoot == NULL)
return;
vector<int> path;
int currentSum = 0;
FindPath(pRoot, expectedSum, path, currentSum);
}
void FindPath(BinaryTreeNode* pRoot, int expectedSum, vector<int>& path,
int currentSum)
{
currentSum += pRoot->m_nValue;
path.push_back(pRoot->m_nValue);
bool isLeaf = (pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL);
//如果是叶子结点并且当前和值和传入整数相等,则打印路径
if (isLeaf && currentSum == expectedSum)
{
vector<int>::iterator iter = path.begin();
for (; iter != path.end(); ++iter)
{
printf("%d ",*iter);
}
printf("\n");
}
if (pRoot->m_pLeft)
FindPath(pRoot->m_pLeft, expectedSum, path, currentSum);
if (pRoot->m_pRight)
FindPath(pRoot->m_pRight, expectedSum, path, currentSum);
//返回父结点前,在路径上删除当前结点
path.pop_back();
}