题目:输入一个整数和一棵二元树。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
二元树节点的数据结构定义为:
struct BinaryTreeNode // a node in the binary tree
{
int m_nValue; // value of node
BinaryTreeNode *m_pLeft; // left child of node
BinaryTreeNode *m_pRight; // right child of node
};
分析:
该题就是判断一条路径value和是否等于给定值,用DFS
程序代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct node
- {
- int value;
- struct node*lchild,*rchild;
- }BTNode;
- #define N 22
- int a[10]; //a数组存放路径
- BTNode* CreateTree(BTNode *L);
- void Fun(BTNode *L,int count,int index);
- int main()
- {
- int count=0,index=0; //count为value和,index为存储在a数组中的元素个数
- BTNode *L=NULL;
- L=CreateTree(L,count,index);
- Fun(L,count,index); //关键函数
- return 0;
- }
- BTNode *CreateTree(BTNode *L)
- {
- BTNode *s=NULL,*cur=NULL;
- L=(BTNode *)malloc(sizeof(BTNode));
- L->value=10;
- cur=L;
- s=(BTNode *)malloc(sizeof(BTNode));
- s->value=5;
- cur->lchild=s;
- cur=s;
- s=(BTNode *)malloc(sizeof(BTNode));
- s->value=4;
- s->lchild=s->rchild=NULL;
- cur->lchild=s;
- s=(BTNode *)malloc(sizeof(BTNode));
- s->value=7;
- s->lchild=s->rchild=NULL;
- cur->rchild=s;
- cur=L;
- s=(BTNode *)malloc(sizeof(BTNode));
- s->value=12;
- s->lchild=s->rchild=NULL;
- cur->rchild=s;
- return L;
- }
- void Fun(BTNode *L,int count,int index)
- {
- int i;
- if (L)
- {
- count+=L->value;
- a[index++]=L->value;
- if (L->lchild==NULL&&L->rchild==NULL)
- {
- if (count==N)
- {
- for (i=0;i<index;i++)
- {
- printf("%d ",a[i]);
- }
- printf("\n");
- }
- }
- else
- {
- Fun(L->lchild,count,index);
- Fun(L->rchild,count,index);
- }
- }
- }