在二元树中找出和为某一值的所有路径

题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数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);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值