#include <iostream>
#include <vector>
using namespace std;
struct node{
int data;
node* lchild;
node* rchild;
};
void find_path(node* r, int exceptedSum, vector<int> &path,
int& curSum);
node* buildBTree(int* a, int &i)
{
if(a==NULL || a[i]==-1)
return NULL;
node* p = new node;
p->data = a[i];
p->lchild = buildBTree(a, ++i);
p->rchild = buildBTree(a, ++i);
return p;
}
void preOrder(node* r)
{
if(r!=NULL)
{
cout<<r->data<<" ";
preOrder(r->lchild);
preOrder(r->rchild);
}else{
cout<<-1<<" ";
}
}
node* buildBTree()
{
int a[] = {10, 5, 4, -1, -1, 7, -1, -1, 12, -1, -1};
int i=0;
return buildBTree(a, i);
}
void find_path(node* r, int exceptedSum)
{
if(r==NULL)
return ;
vector<int> path;
int curSum = 0;
find_path(r, exceptedSum, path, curSum);
}
void find_path(node* r, int exceptedSum, vector<int> &path,
int& curSum)
{
curSum += r->data;
path.push_back(r->data);
if(curSum==exceptedSum && r->lchild==NULL && r->rchild==NULL)
{
cout<<"a path is found: ";
vector<int>::iterator iter = path.begin();
for(; iter != path.end(); iter++)
cout<<*iter<<" ";
cout<<endl;
}
if(r->lchild != NULL)
find_path(r->lchild, exceptedSum, path, curSum);
if(r->rchild != NULL)
find_path(r->rchild, exceptedSum, path, curSum);
curSum -= r->data;
path.pop_back();
}
int main()
{
node* r = buildBTree();
find_path(r, 22);
return 0;
}
上面的关键代码是抄剑指offer上的,如果自己写的话,我更容易写成下面的样子:
bool is_leaf(node* r)
{
if(r==NULL || (r->lchild==NULL && r->rchild==NULL))
return true;
return false;
}
void find_path(node* r, int exceptedSum, vector<int> &path,
int& curSum)
{
if(curSum+r->data < exceptedSum && !is_leaf(r))
{
curSum += r->data;
path.push_back(r->data);
if(r->lchild != NULL)
find_path(r->lchild, exceptedSum, path, curSum);
if(r->rchild != NULL)
find_path(r->rchild, exceptedSum, path, curSum);
curSum -= r->data;
path.pop_back();
}
else if(curSum+r->data==exceptedSum && is_leaf(r))
{
for(int i=0; i<path.size(); i++)
cout<<path[i]<<" ";
cout<<r->data<<endl;
}
}
剑指offer是节点不是页节点都要进行计算,我加了个限制条件“curSum+r->data < exceptedSum”