在data外扩展一个val域,记录要累加的值,通过中序遍历递归,在一个以深度为长度的数组中,更新记录每一个path的所有和值。等于result就打印。
/*You are given a binary tree in which each node contains a value Design an algorithm
to print all paths which sum up to that value Note that it can be any path in the tree
- it does not have to start at the root
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int result = 7;
class Node{
public:
int data;
Node *lchild,*rchild;
int val;
Node(int a=0, Node* l= 0, Node* r = 0):data(a),lchild(l),rchild(r){}
};
class Tree{
public:
Node* root;
Tree():root(0){}
Tree(int ar[],int l){
root = 0;
for(int i = 0; i<l; i++)
insert(ar[i]);
}
void insert(int);
bool is_empty(){ return !root;}
void putval(Node*,int[],int&);
void midorder(Node*,int[],int);
void destroy(Node*);
};
void Tree::insert(int k){
if(is_empty())
root = new Node(k);
else{
Node* temp = root;
Node* parent;
while(temp){
parent =temp;
if(temp->data > k)
temp = temp->lchild;
else temp = temp->rchild;
}
temp = new Node(k);
if(parent->data > k)
parent->lchild = temp;
else parent->rchild = temp;
}
}
void Tree::midorder(Node* r,int val[],int d)
{
if(r){
for(int i =d; i>=0; i--){
val[i] += r->val;
if(val[i] == result){
cout<<result<<"=";
for(int j = i; j<d; j++)
cout<<val[j]-val[j+1]<<"+";
cout<<val[d]<<endl;
}
}
if(r->data == 423)
r = r;
midorder(r->lchild,val,d+1);
midorder(r->rchild,val,d+1);
}
for(int i = 0; i<=d; i++)
val[i] -= val[d];
}
void Tree::putval(Node* r,int v[],int& n)
{
if(r){
putval(r->lchild,v,n);
n = n+1;
r->val = v[n];
putval(r->rchild,v,n);
}
}
void Tree::destroy(Node* r){
if(r){
destroy(r->lchild);
destroy(r->rchild);
delete r;
}
}
int main(){
int ar[]={16,423,5,67,8,9,45,78,777,33,12,11,76,4,43,7};
int v[] ={5,2,1,3,-4,3,3,3,-1,0,-1,4,0,3,2,6};
int val[16] = {0};
Tree ll(ar,16);
int d = -1;
ll.putval(ll.root,v,d);
ll.midorder(ll.root,val,0);
ll.destroy(ll.root);
}