(本博客旨在个人总结回顾)
题目描述:
输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶结点所经过的结点形成一条路径。二叉树结点 的定义如下:
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
例如输入如图4.7 中二叉树和整数22,则打印出两条路径,一条路径包含结点10、12,第二条路径包含结点10、5和7。
完整代码:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
/*
* @name PrintPathSumOfNTree
* @brief 打印二叉树中和为某一值的路径(递归)
* @param [in] BinaryTreeNode * pNode 当前路径遍历的结点
* @param [in] vector<int>vecPath 当前遍历前的路径
* @param [in] int nCurSum 当前遍历结点和
* @param [in] int nSum 完整路径和
* @return void
*/
void PrintPathSumOfNTree(BinaryTreeNode* pNode, vector<int>& vecPath, int nCurSum, int nSum)
{
if (NULL == pNode)
{
return;
}
nCurSum = nCurSum + pNode->m_nValue;
if (nCurSum > nSum)
{
return;
}
vecPath.push_back(pNode->m_nValue);
if (NULL == pNode->m_pLeft && NULL == pNode->m_pRight && nCurSum == nSum)
{
for (vector<int>::iterator it = vecPath.begin(); it != vecPath.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
if (NULL != pNode->m_pLeft)
{
PrintPathSumOfNTree(pNode->m_pLeft, vecPath, nCurSum, nSum);
}
if (NULL != pNode->m_pRight)
{
PrintPathSumOfNTree(pNode->m_pRight, vecPath, nCurSum, nSum);
}
vecPath.pop_back();
}
int _tmain(int argc, _TCHAR* argv[])
{
BinaryTreeNode* pRoot = new BinaryTreeNode();
pRoot->m_nValue = 10;
BinaryTreeNode* pTmp = new BinaryTreeNode();
pTmp->m_nValue = 5;
pRoot->m_pLeft = pTmp;
pTmp = new BinaryTreeNode();
pTmp->m_nValue = 4;
pRoot->m_pLeft->m_pLeft = pTmp;
pTmp = new BinaryTreeNode();
pTmp->m_nValue = 7;
pRoot->m_pLeft->m_pRight = pTmp;
pTmp = new BinaryTreeNode();
pTmp->m_nValue = 12;
pRoot->m_pRight = pTmp;
vector<int> vecPath;
PrintPathSumOfNTree(pRoot, vecPath, 0, 22);
system("pause");
return 0;
}
运行结果: