题目:输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所以路径。从树的根结点开始往下一直到叶子结点所经过的结点形成一条路径。
二叉树的结点结构
struct BinaryTreeNode {
int m_nValue; //用于结点是整数数值的情况
BinaryTreeNode* m_pLeftChild;
BinaryTreeNode* m_pRightChild;
};
//二叉树中和为某一值的路径
void findPath(BinaryTreeNode* pRootNode, int expectedSum) {
if (NULL == pRootNode) {
return;
}
std::vector<int> path;
int currentSum = 0;
findPathSum(pRootNode, expectedSum, path, currentSum);
}
void findPathSum(BinaryTreeNode* pRootNode, int expectedSum,
std::vector<int> &path, int currentSum) {
currentSum = currentSum + pRootNode->m_nValue;
path.push_back(pRootNode->m_nValue);
//判断当前结点是否是叶子结点
bool isLeafNode = NULL == pRootNode->m_pLeftChild
&& NULL == pRootNode->m_pRightChild;
if (currentSum == expectedSum && isLeafNode) {
cout << "一条路径是:" << endl;
std::vector<int>::iterator iter = path.begin();
for (; iter != path.end(); ++iter) {
cout << *iter << '\t';
}
cout << endl;
}
if (NULL != pRootNode->m_pLeftChild) {
findPathSum(pRootNode->m_pLeftChild, expectedSum, path, currentSum);
}
if (NULL != pRootNode->m_pRightChild) {
findPathSum(pRootNode->m_pRightChild, expectedSum, path, currentSum);
}
path.pop_back();
}
测试代码
/*
*
* Created on: 2014-4-26 22:13:11
* Author: danDingCongRong
*/
#include <stddef.h>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int sum = 0, count = 0;
cout << "输入数据的组数:" << endl;
cin >> count;
for (int i = 1; i <= count; ++i) {
cout << "输入第" << i << "组路径和及数据:" << endl;
cin >> sum;
BinaryTreeNode * BTNode = NULL;
BTNode = createIntBinaryTree();
cout << "二叉树的前序遍历(非递归):" << endl;
preorderTravesal_loop(BTNode);
cout << endl;
findPath(BTNode, sum);
}
return 0;
}
注:部分内容参考自剑指offer