在二叉排序树中查找和为给定值的路径

/*
题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。例如:输入整数22 和如下二元树
          10
        / \
       5  12
      / \
     4   7
则打印出两条路径:10, 12 和10, 5, 7。
思路:
1、当访问到某一节点时,把该结点的值添加到当前和变量,且把该结点压入栈中。
2、若结点为叶子结点,且当前和变量==期望的和,则打印栈中的结点值,即为所需的路径。
3、若结点不是叶子结点,继续访问它的左孩子结点,访问它的右孩子结点。
4、删除该结点。包括从当前和变量中减去结点值,从栈中弹出结点值。此时,已回到父结点。
*/

/* 查找路径代码 */
void find_way(BST bst, int expectedSum, struct stack *stk, int *curSum) {
	if (!bst) {
		return;
	}
	*curSum += bst->data;  				//保存所经路径值之和
	stk->data[stk->top++] = bst->data;		//将当前结点值入栈
	int isLeaf = (!bst->left && !bst->right);	//判断是否为叶子结点
	if (expectedSum == *curSum && isLeaf) {		//若为叶子结点,且和为expectedSum,则打印路径
		for (int i = 0; i < stk->top; i++) {
			printf("%d\t", stk->data[i]);
		}
		printf("\n");
	}
	find_way(bst->left, expectedSum, stk, curSum);	//否则递归查找左右子树
	find_way(bst->right, expectedSum, stk, curSum);
	*curSum -= bst->data;				//当前结点处理完后,curSum减当前结点的值,退栈
	stk->top--;
}

/* 完整代码 */
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#define STACK_MAX 30
/* define binary search tree */
typedef struct node {
	int data;
	struct node *left;
	struct node *right;
}*BST;  

/* define simple stack */
struct stack {
	int data[STACK_MAX];
	int top;
};

/* insert node into BST */
void insert(BST *bst, struct node *node) {
	if (!node) {
		return;
	}
	if (!*bst) { //root is empty, then set it to node
		*bst = node;
	} else if (node->data < (*bst)->data) {
		insert(&(*bst)->left, node); //insert to it's left
	} else {
		insert(&(*bst)->right, node);
	}
}

/* use a array to build a binary search tree */
void build_bst(BST *bst, int array[], int n) {
	if (n <= 0) {
		printf("length of array cannot be less than 0");
		exit(EXIT_FAILURE);
	}
	struct node *tmp = NULL;
	for (int i = 0; i < n; i++) {
		if (tmp = (struct node *) malloc(sizeof(struct node))) {
			tmp->left = tmp->right = NULL;
			tmp->data = array[i];
			insert(bst, tmp);
		} else {
			printf("Malloc error\n");
			exit(EXIT_FAILURE);
		}
	}
}

void find_way(BST bst, int expectedSum, struct stack *stk, int *curSum) {
	if (!bst) {
		return;
	}
	*curSum += bst->data;  				//保存所经路径值之和
	stk->data[stk->top++] = bst->data;		//将当前结点值入栈
	int isLeaf = (!bst->left && !bst->right);	//判断是否为叶子结点
	if (expectedSum == *curSum && isLeaf) {		//若为叶子结点,且和为expectedSum,则打印路径
		for (int i = 0; i < stk->top; i++) {
			printf("%d\t", stk->data[i]);
		}
		printf("\n");
	}
	find_way(bst->left, expectedSum, stk, curSum);	//否则递归查找左右子树
	find_way(bst->right, expectedSum, stk, curSum);
	*curSum -= bst->data;				//当前结点处理完后,curSum减当前结点的值,退栈
	stk->top--;
}

int main() {
	BST bst = NULL;
	struct stack stk;
	stk.top = 0;
	int curSum = 0;
	int array[] = {10, 5, 12, 4, 7};
	build_bst(&bst, array, 5);
	find_way(bst, 22, &stk, &curSum);
	return 0;
}
    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/wuxinlonga/article/details/9716385
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞