#include <stdio.h>
#include <stdlib.h>
/*二叉树中和为某一值的路径*/
/*深度优先搜索思想*/
/*创建一个栈 和 一颗二叉树*/
/*栈结构体*/
typedef struct Stack{
int top; /*游标*/
int *space;/*栈空间*/
int len;/*分配栈空间,以及判断栈是否满*/
}Stack;
/*对栈进行初始化*/
void InitStack(Stack *head,int len)
{
head->space = (int *)malloc(sizeof(int)*len);
head->len = len;
head->top = 0;
}
/*判满*/
int Full(Stack *head)
{
return head->top == head->len;
}
/*判空*/
int Empty(Stack *head)
{
return head->top == 0;
}
/*压栈*/
void InStack(Stack *head,int data)
{
head->space[head->top++] = data;
}
/*出栈*/
int OutStack(Stack *head)
{
return head->space[--head->top];
}
/*复位*/
void Reset(Stack *head)
{
head->top = 0;
}
/*释放栈*/
void clearStack(Stack *head)
{
free(head->space);
}
/*二叉树结构体*/
typedef struct TreeNode{
int data;
struct TreeNode *LeftNode;
struct TreeNode *RightNode;
}TreeNode;
/*创建二叉树*/
void CreaTree(TreeNode **head,int data)
{
TreeNode *tepNode = (*head);
if((*head) == NULL)
{
printf("111\n");
(*head) = (TreeNode *)malloc(sizeof(TreeNode));
(*head)->data = data;
(*head)->LeftNode = (*head)->RightNode = NULL;
}
else
{
while(1)
{
if(data > tepNode->data) /*右侧*/
{
if(tepNode->RightNode == NULL)
{
tepNode->RightNode = (TreeNode *)malloc(sizeof(TreeNode));
tepNode->RightNode->data = data;
tepNode->RightNode->LeftNode = tepNode->RightNode->RightNode = NULL;
break;
}
tepNode = tepNode->RightNode;
}
else
{
if(tepNode->LeftNode == NULL)
{
tepNode->LeftNode = (TreeNode *)malloc(sizeof(TreeNode));
tepNode->LeftNode->data = data;
tepNode->LeftNode->LeftNode = tepNode->LeftNode->RightNode = NULL;
break;
}
tepNode = tepNode->LeftNode;
}
}
}
}
/*中序递归遍历*/ /* 递归的本质是压栈 */
void mid_travel(TreeNode *Node)
{
if(Node) /*如果节点不为空,就进入*/
{
mid_travel(Node->LeftNode);
printf("%d ",Node->data);
mid_travel(Node->RightNode);
}
}
/*遍历树,将每一个路径存入堆中,判断和是否是expect_num */
void FindPath(TreeNode *head,Stack *stack,int expect_num)
{
/*将节点的数值,放到堆中*/
InStack(stack,head->data);
/*结束条件*/
if((head->LeftNode == NULL)&&(head->RightNode ==NULL))
{
/*将 expect_num 遍历经过的每一个节点 相减,如果叶子节点的数值正好等于相减之后的 expect_num,则为找到*/
if(head->data == expect_num)
{
printf("find path\n");
for(;Empty(stack)!=1;)
{
printf("%d ",OutStack(stack));
}
}
}
/*不是叶子节点,对子节点进行调用*/
if(head->LeftNode) /*做差*/
FindPath(head->LeftNode,stack,expect_num-head->data);
/*将节点的数值,放到堆中*/
if(head->RightNode)
FindPath(head->RightNode,stack,expect_num-head->data);
/*遍历到叶子结点,如果还不是路径,就出栈叶子节点。。。*/
OutStack(stack);
}
int main(void)
{
Stack stack;
TreeNode *Node=NULL;
int i;
/*对栈进行初始化*/
InitStack(&stack,10);
int str[6]={3,2,1,4,5,6};
/*创建二叉树*/
for(i=0;i<6;i++)
{
CreaTree(&Node,str[i]);
}
/*中序递归遍历*/ /* 递归的本质是压栈 */
mid_travel(Node);
FindPath(Node,&stack,18);
return 0;
}
二叉树中和为某一值的路径
最新推荐文章于 2024-08-23 11:56:42 发布