您的位置:首页 > 其它

打印二叉树中所有和为某一值的路径

2014-07-20 16:02 288 查看
采用前序遍历二叉树,访问过程中保存路径上的结点,到达叶节点时,判断是否满足条件。切记每次左右子树的递归调用返回后,从路径中删除当前根节点。

#include <iostream>
#include <vector>
using namespace std;

struct BiTreeNode{
int val;
BiTreeNode* leftChild;
BiTreeNode* rightChild;
};

void FindPathMatchSum(BiTreeNode* root,
int expectedSum,
int& currentSum,
vector<int>& path)
{
currentSum += root->val;
path.push_back(root->val);

if (root->leftChild == NULL && root->rightChild == NULL){
if (expectedSum == currentSum){
//print path
for (int i = 0; i < path.size(); ++i)
printf("%d ", path[i]);
}
return;
}

if (root->leftChild)
FindPathMatchSum(root->leftChild, expectedSum, currentSum, path);
if (root->rightChild)
FindPathMatchSum(root->rightChild, expectedSum, currentSum, path);
currentSum -= root->val;
path.pop_back();
}

void FindPath(BiTreeNode* root, int expectedSum){
if (root == NULL) return;
vector<int> path;
int currentSum = 0;
FindPathMatchSum(root, expectedSum, currentSum, path);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐