在二元樹中找出和為某一值的所有路徑(樹)

來源:互聯網
上載者:User

在二元樹中找出和為某一值的所有路徑(樹)
題目:輸入一個整數和一棵二元樹。
從樹的根結點開始往下訪問一直到葉結點所經過的所有結點形成一條路徑。
列印出和與輸入整數相等的所有路徑。
例如 輸入整數22和如下二元樹
   10  
   / \  
  5  12   
 / \      
4   7   

則列印出兩條路徑:10, 12和10, 5, 7

#include<stdio.h>#include<assert.h>#include<malloc.h>#define SUM 22typedef struct _Node{int elem;struct _Node *left;struct _Node *right;}Node;int x[20];Node *root=NULL;/*create a bitree*/Node *Bitree(Node *root,int data){if(root==NULL){Node *p=(Node *)malloc(sizeof(Node));assert(p);p->elem=data;p->left=NULL;p->right=NULL;root=p;}else if(data<=root->elem){root->left=Bitree(root->left,data);}else{root->right=Bitree(root->right,data);}return root;}/*output*/void output(int x[],int n){int i=1;Node *p=root;printf("%d\t",p->elem);while(i<=n){if(x[i]==1){p=p->left;printf("%d\t",p->elem);}else if(x[i]==2){p=p->right;printf("%d\t",p->elem);}i++;}printf("\n");}/*find all of sub_trees*/void bitree_sum(Node *root,int sum,int i){if(root==NULL){return;}else{sum+=root->elem;if(sum==SUM){output(x,i);}x[i+1]=1;//to leftbitree_sum(root->left,sum,i+1);x[i+1]=2;//to rightbitree_sum(root->right,sum,i+1);}}int main(){int i=0;int array[]={10,5,4,7,12};int len=sizeof(array)/sizeof(array[0]);/*形成二叉排序樹*/while(i<len){root=Bitree(root,array[i]);i++;}/*輸出和為sum的所有路徑*/bitree_sum(root,0,0);return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.