题目来源:http://bbs.youkuaiyun.com/topics/350118968
4.在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
当访问到某一结点时,把该结点添加到路径上,并累加当前结点的值。
如果当前结点为叶结点并且当前路径的和刚好等于输入的整数,则当前的路径符合要求,我们把它打印出来。
如果当前结点不是叶结点,则继续访问它的子结点。当前结点访问结束后,递归函数将自动回到父结点。
因此我们在函数退出之前要在路径上删除当前结点并减去当前结点的值,以确保返回父结点时路径刚好是根结点到父结点的路径。
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
struct TreeNode
{
TreeNode *left;
TreeNode *right;
int value;
};
int path[100];
int top = -1;
void addTreeNode(TreeNode *¤t, int data)
{
if(current != NULL)
{
if(current->value > data)
addTreeNode(current->left, data);
else if(current->value < data)
addTreeNode(current->right, data);
else
cout << "repeated data" << endl;
}
else
{
TreeNode *node = new TreeNode();
node->left = NULL;
node->right = NULL;
node->value = data;
current = node;
}
}
void search(TreeNode *current, int sum, int s)
{
path[top++] = current->value;
if(current->left == NULL && current->right == NULL && sum+current->value == s)
{
for(int i = 0; i < top; i++)
cout << path[i] << " ";
cout << endl;
}
if(current->value+sum >= s)
{
top--;
return;
}
if(current->left != NULL)
search(current->left, sum+current->value, s);
if(current->right != NULL)
search(current->right, sum+current->value, s);
top--;
}
int main()
{
TreeNode *root = new TreeNode;
int a[10] = {10, 5, 12, 4, 7};
for(int i = 0; i < 5; i++)
addTreeNode(root, a[i]);
search(root, 0, 22);
return 0;
}