在 二叉樹中找出和爲某一值的全部路徑

從樹的根結點開始往下訪問一直到葉結點所通過的全部結點造成一條路徑。
打印出和與輸入整數相等的全部路徑。
例如 輸入整數22和以下二元樹
      10   
      / \   
     5  12   
      / \    
      4    7
則打印出兩條路徑:10, 12和10, 5, 7。node


先序遍歷樹便可獲得結果。算法

算法: FindPath(BTree * root,int sum,int target,Stack * s) 用來計算,sum爲棧中的元素的和,target爲目標值。數組

到達一個節點以後計算當前節點和sum的和,若是爲target,輸出路徑返回,若是大於target,則直接返回,若是小於,則將當前節點的值入棧,更新sum的值,繼續遍歷,遍歷完成以後,也就是從當前節點返回的時候,將其從棧中彈出,更新sumspa

代碼以下(GCC編譯經過):3d

#include "stdio.h"
#include "stdlib.h"
#define MAXSIZE 8

typedef struct node
{
	int data;
	struct node * left;
	struct node * right;
}BTree;

typedef struct 
{
	int top;
	int data[MAXSIZE];
}Stack;

BTree * CreatTree(int a[],int n);
void Iorder(BTree * root);
void Porder(BTree * root);
void FindPath(BTree * root,int sum,int target,Stack * stack);
void InitStack(Stack * stack);
void Push(Stack * s,int val);
int Pop(Stack *s);

int main(void)
{
	int array[MAXSIZE] = {5,3,8,7,2,4,1,9},target;
	BTree * root;
	Stack stack;
	
	target = 12;
	root = CreatTree(array,MAXSIZE);
	InitStack(&stack);

	printf("二叉樹內元素升序排列:");
	Iorder(root);
	printf("\n");

	printf("目標值:%d,路徑:",target);
	FindPath(root,0,target,&stack);

	printf("\n");
	return 0;
}

//根據數組生成二叉排序樹
BTree * CreatTree(int a[],int n)
{
	BTree * root ,*p,*cu,*pa;
	int i;
	
	root = (BTree *)malloc(sizeof(BTree));
	root->data = a[0]; 
	root->left = root->right =NULL;
	
	for(i=1;i<n;i++)
	{
		p = (BTree *)malloc(sizeof(BTree));
		p->data = a[i];
		p->left = p->right =NULL;
		cu = root;

		while(cu)
		{
			pa = cu;
			if(cu->data > p->data)
				cu = cu->left;
			else
				cu = cu->right;
		}
		if(pa->data > p->data)
			pa->left = p;
		else
			pa->right = p;
	}	

	return root;
}

//中根遍歷,打印二叉樹
void Iorder(BTree * root)
{
	if(root)
	{		
		Iorder(root->left);
		printf("%3d",root->data);
		Iorder(root->right);
	}
}

//尋找路徑
void FindPath(BTree * root,int sum,int target,Stack * s)
{
	int i;

	if(!root)
		return ;
	if(sum + root->data == target)
	{
		Push(s,root->data);
		for(i = 0;i<s->top;i++)
			printf("%3d",s->data[i]);
		return;
	}

	else if(sum + root->data > target)
	     {
		return;
	     }
	     else
	     {
		Push(s,root->data);
		sum += root->data;
		FindPath(root->left,sum,target,s);
		FindPath(root->right,sum,target,s);
		sum -= root->data;
		Pop(s);
	     }
}

//初始化棧
void InitStack(Stack * s)
{
	s->top = 0;
}

//入棧
void Push(Stack *s,int val)
{
	if(s->top == MAXSIZE)
	{
		printf("棧滿,沒法入棧!\n");
		return;
	}
	s->data[(s->top)++] = val;

}

//出棧
int Pop(Stack *s)
{
	if(s->top == 0)
	{
		printf("棧空,沒法出棧!\n");
		return;
	}
	
	return s->data[--(s->top)];
}

參考內容:
算法思想描述來源與互聯網
算是實現原創
相關文章
相關標籤/搜索