1. 程式人生 > >二叉樹的遞歸遍歷 The Falling Leaves UVa 699

二叉樹的遞歸遍歷 The Falling Leaves UVa 699

輸入 out col ges while com cst bsp images

技術分享

題意:對於每一棵樹,每一個結點都有它的水平位置,左子結點在根節點的水平位置-1,右子節點在根節點的位置+1,從左至右輸出每個水平位置的節點之和

解題思路:由於上題所示的遍歷方式如同二叉樹的前序遍歷,與天平那題不同,本題不需要構造出完整的結點左右子樹,只需要構造出結點的相對位置,每次輸入一個結點樹,若為-1,則返回,否則依次遞歸執行input(p-1)與input(p+1)。

代碼如下:

 1 #include<stdio.h>
 2 #include<cstring>
 3 #include<iostream>
 4 using namespace std;
5 const int MAXX=260000; 6 int sum[MAXX]; 7 void input(int p){ 8 int root; 9 scanf("%d",&root); 10 if(root==-1) return; 11 sum[p]+=root; 12 input(p-1); 13 input(p+1); 14 } 15 16 bool init(){ 17 int root; 18 scanf("%d",&root); 19 if(root==-1) return false
; 20 int d; 21 memset(sum,0,sizeof(sum)); 22 d=MAXX/2; 23 sum[d]=root; 24 input(d-1); 25 input(d+1); 26 } 27 28 int main(){ 29 freopen("in.txt","r",stdin); 30 int i=1; 31 while(init()){ 32 printf("Case %d:\n",i); 33 int num=0; 34 while(sum[num]==0
){ 35 num++; 36 } 37 while(sum[num]!=0){ 38 printf("%d%c",sum[num],sum[num+1]? :\n\n ); 39 num++; 40 } 41 cout<<endl; 42 i++; 43 } 44 }

二叉樹的遞歸遍歷 The Falling Leaves UVa 699