问题是这样的,在一棵以root为根的树中,找出以root为起点的所有路径,要求路径中节点的值相加等于给定的数值。这个问题很简单,甚至于想都不用想就知道遍历树一遍就可以解决。
找出符合要求的路径,其实就是下面这个递归表达式:
1.求出以root为节点和等于v的路径;
2.如果root->value等于v,那么找到一条路径,返回;
3.如果root->value大于v,那么就分别找出以root左右孩子为根的和等于v – root->value的路径;
4.如果root->value小于v,那么就不存在符合条件的路径。
代码表示如下。
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
struct tree {
int value;
struct tree *lchild;
struct tree *rchild;
};
struct tree *insert(struct tree *root, int value)
{
if (root) {
if (value < root->value) {
root->lchild = insert(root->lchild, value);
} else {
root->rchild = insert(root->rchild, value);
}
} else {
root = new struct tree;
root->value = value;
root->lchild = 0;
root->rchild = 0;
}
return root;
}
void print_tree_prefix(struct tree *root, string pfx)
{
if (root) {
if (root->lchild) {
cout << pfx << "|" << endl;
if (root->rchild) {
cout << pfx << "|-<L> " << root->lchild->value << endl;
print_tree_prefix(root->lchild, pfx + "| ");
} else {
cout << pfx << "`-<L> " << root->lchild->value << endl;
}
}
if (root->rchild) {
cout << pfx << "|" << endl;
cout << pfx << "`-<R> " << root->rchild->value << endl;
print_tree_prefix(root->rchild, pfx + " ");
}
}
}
void print_tree(struct tree *root)
{
if (root) {
cout << root->value << endl;
print_tree_prefix(root, "");
}
}
string itos(int i)
{
string str;
stringstream s;
s << i;
s >> str;
return str;
}
void sum_prefix(struct tree *root, int v, string pfx)
{
if (root) {
if (v == root->value) {
cout << pfx << root->value << endl;
} else if (v > root->value) {
v -= root->value;
pfx += itos(root->value) + "+";
sum_prefix(root->lchild, v, pfx);
sum_prefix(root->rchild, v, pfx);
}
}
}
void sum(struct tree *root, int v)
{
if (root) {
sum_prefix(root, v, itos(v) + "=");
}
}
int main()
{
struct tree *root = 0;
root = insert(root, 10);
root = insert(root, 5);
root = insert(root, 4);
root = insert(root, 7);
root = insert(root, 12);
root = insert(root, 23);
root = insert(root, 1);
root = insert(root, 6);
root = insert(root, 2);
print_tree(root);
sum(root, 22);
return 0;
}