题目
输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路
当用前序遍历的方式访问到某一结点时,我们把结点添加到路径上,并累加该结点的值。如果该结点为叶结点并且路径中结点值的和刚好等于输入的整数,则当前的路径符合要求,将它打印出来。如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到它的父结点。因此在函数退出前,要在路径上删除当前结点,并减去当前结点的值,以确保返回父结点的路径刚好是从根结点到父结点的路径。
代码
#include <iostream>
#include <vector>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
void FindPath
(
BinaryTreeNode* pRoot,
int expectedSum,
std::vector<int>& path,
int& currentSum
)
{
currentSum += pRoot->m_nValue;
path.push_back(pRoot->m_nValue);
// 如果是叶子结点,并且路径结点的和等于输入的值
// 打印出这条路径
bool isLeaf = pRoot->m_pLeft == nullptr && pRoot->m_pRight == nullptr;
if(currentSum == expectedSum && isLeaf)
{
cout << "A path is found: ";
for (auto item : path)
{
cout << item << "\t";
}
cout << endl;
}
// 如果不是结点,则遍历它的子结点
if (pRoot->m_pLeft != nullptr)
FindPath(pRoot->m_pLeft, expectedSum, path, currentSum);
if (pRoot->m_pRight != nullptr)
FindPath(pRoot->m_pRight, expectedSum, path, currentSum);
// 在返回到父结点之前,在路径上删除当前结点,
// 并在currentSum中减去当前结点的值
currentSum -= pRoot->m_nValue;
path.pop_back();
}
void FindPath(BinaryTreeNode* pRoot, int expectedSum)
{
if (pRoot == nullptr)
return;
std::vector<int> path;
int currentSum = 0;
FindPath(pRoot, expectedSum, path, currentSum);
}
int main()
{
BinaryTreeNode node_1 = {4, nullptr, nullptr};
BinaryTreeNode node_2 = {7, nullptr, nullptr};
BinaryTreeNode node_3 = {12, nullptr, nullptr};
BinaryTreeNode node_4 = {5, &node_1, &node_2};
BinaryTreeNode root = {10, &node_4, &node_3};
FindPath(&root,22);
return EXIT_SUCCESS;
}