题目大意:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
九度OJ链接:http://ac.jobdu.com/problem.php?pid=1368
分析:题目就是先输入一个树,然后在树中找到从根到叶子的路径,使得路径上的节点值之和为给定的某个值。如果有多条,注意题目要求按照字典序输出这些路径。
C++实现:
#include <iostream>
#include <stdio.h>
#include <vector>
#include <memory.h>
#include <string>
#include <algorithm>
#include <iomanip>
#include <map>
#include <fstream>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
using namespace std;
struct Node //树节点定义
{
int value;
int id;
Node *left;
Node *right;
int l_index;
int r_index;
Node(int val)
{
value = val;
left = NULL;
right = NULL;
}
};
void output(vector<int> &path)<span style="white-space:pre"> </span>//输出找到的路径
{
printf("A path is found:");
for(int i = 0; i < path.size(); i ++)
{
printf(" %d", path[i]);
}
printf("\n");
}
int sum;
void getRootToLeafPath(Node *root, int k, vector<int> &path)<span style="white-space:pre"> </span>//先序遍历,查找满足条件的路径
{
sum += root->value;
path.push_back(root->id);
if(root->left == NULL && root->right == NULL)
{
if(sum == k)
{
output(path);
}
sum -= root->value;
path.pop_back();
return;
}
if(root->left)
getRootToLeafPath(root->left, k, path);
if(root->right)
getRootToLeafPath(root->right, k, path);
sum -= root->value;
path.pop_back();
}
void input()
{
// freopen("c:/input.txt","r",stdin);
int n, k;
while(scanf("%d%d", &n,&k) != EOF)
{
vector<Node*> node;
Node *root = NULL, *tmp;
int x, a, b;
while(n-- > 0)
{
scanf("%d%d%d", &x,&a,&b);
tmp = new Node(x);
if(a > b)<span style="white-space:pre"> </span>//注意此处调整,为满足输出的字典序要求
swap(a,b);
tmp->l_index = a;
tmp->r_index = b;
node.push_back(tmp);
}
root = node[0];
for(int i = 0; i < node.size(); i ++)
{
node[i]->id = i + 1;
if(node[i]->l_index != -1)
node[i]->left = node[node[i]->l_index - 1];
if(node[i]->r_index != -1)
node[i]->right = node[node[i]->r_index - 1];
}
sum = 0;
vector<int> path;
printf("result:\n");
getRootToLeafPath(root, k, path);
// printf("\n");
}
}
int main()
{
input();
return 0;
}