题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
#include "stdlib.h"
#include "stdio.h"
typedef struct BTNode
{
int data;
struct BTNode *lnode;
struct BTNode *rnode;
}BTNode;
BTNode *CreateTree(int pre[], int in[], int l1, int r1, int l2, int r2){
BTNode *s;
int i;
if(l1 > r1)
return NULL;
s = (BTNode *)malloc(sizeof(BTNode));
s->lnode = s->rnode = NULL;
for(i=l2; i<=r2; ++i){
if(pre[l1] == in[i]){
break;
}
}
s->data = in[i];
s->lnode = CreateTree(pre, in, l1+1, l1+i-l2, l2, i-1);
s->rnode = CreateTree(pre, in, l1+i-l2+1, r1, i+1, r2);
return s;
}
void PrePrint(BTNode *p){
if(p != NULL){
printf("%d ", p->data);
PrePrint(p->lnode);
PrePrint(p->rnode);
}
}
void InPrint(BTNode *p){
if(p != NULL){
InPrint(p->lnode);
printf("%d ", p->data);
InPrint(p->rnode);
}
}
typedef struct MyStack{
int top;
int data[50];
}MyStack;
void FindSumPath(BTNode *p, MyStack &mystack, int targetSum, int ¤tSum){
if(!p)
return;
currentSum += p->data;
++mystack.top;
mystack.data[mystack.top]= p->data;
printf("top=%d, data=%d, currentSum=%d\n", mystack.top, mystack.data[mystack.top], currentSum);
bool isLeaf = !p->lnode && !p->rnode;
if(currentSum == targetSum && isLeaf){
int i = mystack.top;
while(i != -1){
printf("%d ", mystack.data[i]);
--i;
}
putchar('\n');
}
FindSumPath(p->lnode, mystack, targetSum, currentSum);
FindSumPath(p->rnode, mystack, targetSum, currentSum);
currentSum -= p->data;
--mystack.top;
}
void main(){
int pre[] = {10, 5, 4, 7, 12};
int in[] = {4, 5, 7, 10, 12};
BTNode *p;
p = CreateTree(pre, in, 0, 4, 0, 4);
MyStack st;
st.top = -1;
int currentSum = 0;
FindSumPath(p, st, 22, currentSum);
}