代码:
struct BinaryTreeNode
{
int m_value;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
void findPath(BinaryTreeNode* pRoot, int sum, vector<int>& path, int currentSum)
{
currentSum += pRoot->m_value;
path.push_back(pRoot->m_value);
if (currentSum == sum && (pRoot->m_pLeft == nullptr) && (pRoot->m_pRight == nullptr))
{
cout << "A path is found: ";
vector<int>::iterator iter = path.begin();
for (; iter != path.end(); ++iter)
{
cout << *iter << " ";
}
cout << endl;
}
//若左子树不为空
if (pRoot->m_pLeft != nullptr)
findPath(pRoot->m_pLeft,sum,path,currentSum);
//若右子树不为空
if (pRoot->m_pRight != nullptr);
findPath(pRoot->m_pRight, sum, path, currentSum);
}
//打印树的路径
void PrintPathOfBST(BinaryTreeNode* pRoot, int sum)
{
if (!pRoot)
return;
vector<int> path;
int currentSum = 0;
findPath(pRoot, sum, path, currentSum);
}