列印從根結點到葉子結點的路徑(遞迴)

來源:互聯網
上載者:User

//列印從根結點到葉子結點的路徑
 
#include<stdio.h>
#include<malloc.h>

typedef struct tree
{
    int data;
    struct tree *lchild,*rchild;       
}tree,*stree;

typedef struct stack
{
   char da[100];
   int top;       
}stack;

stack s;

void push(stack &s,char da)
{
  s.top++;
  s.da[s.top]=da;    
}

void pop(stack &s)
{
  s.top--;    
}

void display(stack s)
{
     int i;
     printf("路徑:/n");
   for(i=1;i<=s.top;i++)
   printf("%c",s.da[i]);
   printf("/n");    
}

void create(stree &t)
{
     char ch;
  scanf("%c",&ch);
  if(ch==' ') t=NULL;
  else
  {
  t=(stree)malloc(sizeof(tree));
  t->data=ch;
  create(t->lchild);
  create(t->rchild);    
  }         
}

void path(stree t)
{
     if(t)
 {
    push(s,t->data);
    if(t->lchild==NULL&&t->rchild==NULL)
    {display(s);}
    else
    {
    path(t->lchild);
    path(t->rchild);    
    }
   pop(s);//注意這裡的位置,不可以放到display()後面
 }    
}

int main()
{
   stree t=NULL;
   while(1)
   {
   s.top=0;
   printf("輸入序列:/n");
   create(t);
   //pre(t);
   printf("/n");
   path(t);
   printf("/n");
   }
}
/*
輸入序列:
abd  ef   c fh

路徑:
abd
路徑:
abef
路徑:
acfh
*/
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.