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

来源:互联网 发布:手机看病软件 编辑:程序博客网 时间:2024/06/01 11:45

题目:输入一个整数和一棵二元树。


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


程序代码:

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <string.h>  
  4.   
  5. typedef struct node  
  6. {  
  7.     int value;  
  8.     struct node*lchild,*rchild;  
  9. }BTNode;  
  10.   
  11. #define N 22  
  12. int a[10];   //a数组存放路径  
  13.   
  14. BTNode* CreateTree(BTNode *L);  
  15. void Fun(BTNode *L,int count,int index);  
  16.   
  17. int main()  
  18. {  
  19.     int count=0,index=0;   //count为value和,index为存储在a数组中的元素个数  
  20.     BTNode *L=NULL;  
  21.     L=CreateTree(L,count,index);  
  22.     Fun(L,count,index);    //关键函数  
  23.     return 0;  
  24. }  
  25.   
  26. BTNode *CreateTree(BTNode *L)  
  27. {  
  28.     BTNode *s=NULL,*cur=NULL;  
  29.   
  30.     L=(BTNode *)malloc(sizeof(BTNode));  
  31.     L->value=10;  
  32.   
  33.     cur=L;  
  34.     s=(BTNode *)malloc(sizeof(BTNode));  
  35.     s->value=5;  
  36.     cur->lchild=s;  
  37.   
  38.     cur=s;  
  39.     s=(BTNode *)malloc(sizeof(BTNode));  
  40.     s->value=4;  
  41.     s->lchild=s->rchild=NULL;  
  42.     cur->lchild=s;  
  43.   
  44.     s=(BTNode *)malloc(sizeof(BTNode));  
  45.     s->value=7;  
  46.     s->lchild=s->rchild=NULL;  
  47.     cur->rchild=s;  
  48.   
  49.     cur=L;  
  50.     s=(BTNode *)malloc(sizeof(BTNode));  
  51.     s->value=12;  
  52.     s->lchild=s->rchild=NULL;  
  53.     cur->rchild=s;  
  54.   
  55.     return L;  
  56. }  
  57.   
  58. void Fun(BTNode *L,int count,int index)  
  59. {  
  60.     int i;  
  61.     if (L)  
  62.     {  
  63.          count+=L->value;  
  64.          a[index++]=L->value;  
  65.          if (L->lchild==NULL&&L->rchild==NULL)  
  66.          {  
  67.              if (count==N)  
  68.              {  
  69.                  for (i=0;i<index;i++)  
  70.                  {  
  71.                      printf("%d  ",a[i]);  
  72.                  }  
  73.                  printf("\n");  
  74.              }  
  75.          }  
  76.          else  
  77.          {  
  78.              Fun(L->lchild,count,index);  
  79.              Fun(L->rchild,count,index);  
  80.          }  
  81.           
  82.     }  
  83. }  


原创粉丝点击