码迷,mamicode.com
首页 > 其他好文 > 详细

输出二叉树中路径上结点值之和为给定值的所有路径

时间:2016-07-11 21:18:03      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

#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;
}

/*

 

*/

输出二叉树中路径上结点值之和为给定值的所有路径

标签:

原文地址:http://www.cnblogs.com/wuxiangli/p/5661527.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!