输出二叉树中路径上结点值之和为给定值的所有路径
#include<iostream>
#include<vector>
#include<algorithm>
#include<stdint.h>
using namespace std;
#include<list>
#include<map>
#include<queue>
struct node
{
int val;
node* left, *right;
node(int _val) :val(_val), left(NULL), right(NULL){}
};
void findSum(node* head, int sum, vector<int>& paths, int level)
{
if (head == NULL) return;
int tmp = sum;
paths.push_back(head->val);
for (int i = level; i >= 0; i--)
{
tmp -= paths[i];
if (tmp == 0)
{
for (int j = i; j <= level; j++)
cout << paths[j] << " ";
cout << endl;
}
}
findSum(head->left, sum, paths, level + 1);
findSum(head->right, sum, paths, level + 1);
paths.pop_back();
}
int main()
{
node n1(2), n2(3), n3(2), n4(-4), n5(3), n6(6), n7(1), n8(3), n9(1), n10(2);
n1.left = &n2;
n1.right = &n3;
n2.left = &n4;
n2.right = &n5;
n3.left = &n6;
n3.right = &n7;
n4.left = &n8;
n8.left = &n9;
n9.left = &n10;
vector<int> paths;
findSum(&n1, 5, paths, 0);
return 0;
}
/*
*/