您的位置:首页 > Web前端

二叉树中和为某一值的路径(剑指offer25)

2014-04-26 22:56 246 查看
题目:输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所以路径。从树的根结点开始往下一直到叶子结点所经过的结点形成一条路径。

二叉树的结点结构

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: