来自剑指offer 面试题25
题目:输入一棵二叉树,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶子节点所经过的节点形成一条路径。
之前讲了怎么求根节点到叶子节点的路径。所以对于这一个题,只需要稍微在之前的基础上改动一下就可以了!
看代码:
//打印路径
void printPath(vector<int>&path){
vector<int>::const_iterator iter = path.begin(); //打印出来
for (; iter != path.end() - 1; ++iter)
cout << *iter << "->";
cout << *iter;
cout << endl;//换行
}
void FindPath(BinaryTreeNode*pRoot, int nExpectedSum, std::vector<int> & path, int nCurrrentSum){
if (pRoot==NULL)
{
return;
}
nCurrrentSum += pRoot->m_nValue;
path.push_back(pRoot->m_nValue);
//到了叶节点并且路径节点的和等于输入的值,则打印这条路径
if ((pRoot->m_pLeft==NULL&&pRoot->m_pRight==NULL)&&nCurrrentSum==nExpectedSum)
{
printPath(path);
}
//不是叶节点则遍历其子节点
if (pRoot->m_pLeft!=NULL)
{
FindPath(pRoot->m_pLeft, nExpectedSum, path, nCurrrentSum);
}
if (pRoot->m_pRight!=NULL)
{
FindPath(pRoot->m_pRight, nExpectedSum, path, nCurrrentSum);
}
//返回父节点之前,在路径上删除当前
path.pop_back();
}
void FindPath(BinaryTreeNode*pRoot, int nExpectedSum){
vector<int> path;
int nCurrentSum = 0;
//核心函数
FindPath(pRoot, nExpectedSum, path, nCurrentSum);
}
以下面的二叉树作为测试:
下面是测试代码:
//先序创建二叉树
void CreatBTree(BinaryTreeNode *&root)
{
int nValue = 0;
cin >> nValue;
if (-1 == nValue)
{
return;
}
else
{
root = new BinaryTreeNode();
root->m_nValue = nValue;
CreatBTree(root->m_pLeft);
CreatBTree(root->m_pRight);
}
}
int main(){
BinaryTreeNode*T;
cout << "先序构建二叉树:" << endl;
CreatBTree(T);
cout << "找到和为18的路径:" << endl;
FindPath(T, 18);
return 0;
}
输出结果为: