7-8 List Leaves(25 point(s))

遍历树结构打印叶子节点
本文介绍了一种遍历树形结构的方法,通过输入树的节点及其子节点信息,按从上到下、从左到右的顺序列出所有的叶子节点。文章提供了完整的C语言实现代码,展示了如何构建树结构、确定根节点并进行层次遍历。
7-8 List Leaves(25 point(s))

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each test case, print in one line all the leaves' indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

Sample Output:

4 1 5

code:只要解决了储存问题和树根的判断这个题就解决了
 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int pre[20];//记录每个节点的父亲节点是几号
struct node{
   int l;
   int r;
}tre[20];//用一个tre结构体数组表示树,tre[i]表示i为根节点时,l r是它的左右儿子,没有初始化为-1;
int n;
int main(){
    int i;
    scanf("%d",&n);
    getchar();
    for(i = 0; i < n; i++){//初始化
        tre[i].l = -1;
        tre[i].r = -1;
        pre[i] = -1;
    }
    for(i = 0; i < n; i++){
        char a[5];
        gets(a);//每行输入i号节点的两个儿子,用字符串方便输入
        if(a[0]>='0'&&a[0]<='9'){//如果第一个是数字
            int lson = a[0]-'0';//转换成数字
            pre[lson] = i;//左儿子的父亲记为i
            tre[i].l = lson;//i的左儿子记为lson
        }
        if(a[2]>='0'&&a[2]<='9'){//右儿子是数字
            int rson = a[2]-'0';//转换成int
            pre[rson] = i;//父亲记为i
            tre[i].r = rson;//i号节点记录右儿子
        }
    }
    int rt;
    for(i = 0; i < n; i++){
        if(pre[i]==-1){//如果有个点没有父亲,即父亲数组的值是-1,说明这个点是树根节点 
            rt = i;
            break;
        }
    }
    //然后从树根开始搜索
	int q[20];//数组模拟队列 
	int vis[20];//标记数组
	int ans[20];//答案数组 
	memset(vis,0,sizeof(vis)); 
	int head = 0,tail = 0;
	int cnt = 0;
	q[tail++] = rt;
	while(head<tail){//相当于层序遍历 
	    int	subtre = q[head];
	   // printf("%d  ",subtre);
		if(tre[subtre].l==-1&&tre[subtre].r==-1){
			ans[cnt++] = subtre;//如果没有左右儿子,说明是叶子,放入答案数组 
		}
		if(tre[subtre].l!=-1){//如果这个点有左儿子,并且没有访问过入队 
			q[tail++] = tre[subtre].l;
		}
		if(tre[subtre].r!=-1){//如果这个点有右儿子,并且没有访问过入队 
			q[tail++] = tre[subtre].r;
		}
		head++;
	}
	for(i = 0; i < cnt; i++){
		if(i==0)printf("%d",ans[i]);
		else printf(" %d",ans[i]);
	}
	puts("");
    return 0;
}


[D] format -- Set variables' output format (View complete PDF manual entry) Syntax Set formats format varlist %fmt format %fmt varlist Set style of decimal point set dp {comma|period} [, permanently] Display long formats format [varlist] where %fmt can be a numerical, date, business calendar, or string format. Numerical %fmt Description Example ------------------------------------------------------- right-justified %#.#g general %9.0g %#.#f fixed %9.2f %#.#e exponential %10.7e %21x hexadecimal %21x %16H binary, hilo %16H %16L binary, lohi %16L %8H binary, hilo %8H %8L binary, lohi %8L right-justified with commas %#.#gc general %9.0gc %#.#fc fixed %9.2fc right-justified with leading zeros %0#.#f fixed %09.2f left-justified %-#.#g general %-9.0g %-#.#f fixed %-9.2f %-#.#e exponential %-10.7e left-justified with commas %-#.#gc general %-9.0gc %-#.#fc fixed %-9.2fc ------------------------------------------------------- You may substitute comma (,) for period (.) in any of the above formats to make comma the decimal point. In %9,2fc, 1000.03 is 1.000,03. Or you can set dp comma. date %fmt Description Example ------------------------------------------------------- right-justified %tc date/time %tc %tC date/time %tC %td date %td %tw week %tw %tm month %tm %tq quarter %tq %th half-year %th %ty year %ty %tg generic %tg left-justified %-tc date/time %-tc %-tC date/time %-tC %-td date %-td etc. ------------------------------------------------------- There are many variations allowed. See [D] Datetime display formats. business calendar %fmt Description Example ------------------------------------------------------- %tbcalname a business calendar %tbsimple [:datetime-specifiers] defined in calname.stbcal ------------------------------------------------------- See [D] Datetime business calendars. string %fmt Description Example ------------------------------------------------------- right-justified %#s string %15s left-justified %-#s string %-20s centered %~#s string %~12s ------------------------------------------------------- The centered format is for use with display only. Menu Data > Variables Manager Description format varlist %fmt and format %fmt varlist are the same commands. They set the display format associated with the variables specified. The default formats are a function of the type of the variable: byte %8.0g int %8.0g long %12.0g float %9.0g double %10.0g str# %#s strL %9s set dp sets the symbol that Stata uses to represent the decimal point. The default is period, meaning that one and a half is displayed as 1.5. format [varlist] displays the current formats associated with the variables. format by itself lists all variables that have formats too long to be listed in their entirety by describe. format varlist lists the formats for the specified variables regardless of their length. format * lists the formats for all the variables. Links to PDF documentation Quick start Remarks and examples The above sections are not included in this help file. Option permanently specifies that, in addition to making the change right now, the dp setting be remembered and become the default setting when you invoke Stata. Remarks Remarks are presented under the following headings: The %f format The %fc format The %g format The %gc format The %e format The %21x format The %16H and %16L formats The %8H and %8L formats The %t format The %s format Examples Video example The %f format In %w.df, w is the total output width, including sign and decimal point, and d is the number of digits to appear to the right of the decimal point. The result is right-justified. The number 5.139 in %12.2f format displays as ----+----1-- 5.14 When d==0, the decimal point is not displayed. The number 5.14 in %12.0f format displays as ----+----1-- 5 %-w.df works the same way, except that the output is left-justified in the field. The number 5.139 in %-12.2f displays as ----+----1-- 5.14 The %fc format %w.dfc works like %w.df except that commas are inserted to make larger numbers more readable. w records the total width of the result, including commas. The number 5.139 in %12.2fc format displays as ----+----1-- 5.14 The number 5203.139 in %12.2fc format displays as ----+----1-- 5,203.14 As with %f, if d==0, the decimal point is not displayed. The number 5203.139 in %12.0fc format displays as ----+----1-- 5,203 As with %f, a minus sign may be inserted to left justify the output. The number 5203.139 in %-12.0fc format displays as ----+----1-- 5,203 The %g format In %w.dg, w is the overall width, and d is usually specified as 0, which leaves up to the format the number of digits to be displayed to the right of the decimal point. If d!=0 is specified, then not more than d digits will be displayed. As with %f, a minus sign may be inserted to left-justify results. %g differs from %f in that (1) it decides how many digits to display to the right of the decimal point, and (2) it will switch to a %e format if the number is too large or too small. The number 5.139 in %12.0g format displays as ----+----1-- 5.139 The number 5231371222.139 in %12.0g format displays as ----+----1-- 5231371222 The number 52313712223.139 displays as ----+----1-- 5.23137e+10 The number 0.0000029394 displays as ----+----1-- 2.93940e-06 The %gc format %w.dgc is %w.dg, with commas. It works in the same way as the %g and %fc formats. The %e format %w.de displays numeric values in exponential format. w records the width of the format. d records the number of digits to be shown after the decimal place. w should be greater than or equal to d+7 or, if 3-digit exponents are expected, d+8. The number 5.139 in %12.4e format is ----+----1-- 5.1390e+00 The number 5.139*10^220 is ----+----1-- 5.1390e+220 The %21x format The %21x format is for those, typically programmers, who wish to analyze routines for numerical roundoff error. There is no better way to look at numbers than how the computer actually records them. The number 5.139 in %21x format is ----+----1----+----2- +1.48e5604189375X+002 The number 5.125 is ----+----1----+----2- +1.4800000000000X+002 Reported is a signed, base-16 number with base-16 point, the letter X, and a signed, 3-digit base-16 integer. Call the two numbers f and e. The interpretation is f*2^e. The %16H and %16L formats The %16H and %16L formats show the value in the IEEE floating point, double-precision form. %16H shows the value in most-significant-byte-first (hilo) form. %16L shows the number in least-significant-byte-first (lohi) form. The number 5.139 in %16H is ----+----1----+- 40148e5604189375 The number 5.139 in %16L is ----+----1----+- 75931804568e1440 The format is sometimes used by programmers who are simultaneously studying a hexadecimal dump of a binary file. The %8H and %8L formats %8H and %8L are similar to %16H and %16L but show the number in IEEE single-precision form. The number 5.139 in %8H is ----+--- 40a472b0 The number 5.139 in %8L is ----+--- b072a440 The %t format The %t format displays numerical variables as dates and times. See [D] Datetime display formats. The %s format The %ws format displays a string in a right-justified field of width w. %-ws displays the string left-justified. "Mary Smith" in %16s format is ----+----1----+- Mary Smith "Mary Smith" in %-16s format is ----+----1----+- Mary Smith In addition, in some contexts, particularly display (see [P] display), %~ws is allowed, which centers the string. "Mary Smith" in %~16s format is ----+----1----+- Mary Smith Examples Four values displayed in different numeric display formats +---------------------------------------------------------------------+ | %9.0g %9.0gc %9.2f %9.2fc %-9.0g %09.2f %9.2e | |---------------------------------------------------------------------| | 12345 12,345 12345.00 12,345.00 12345 012345.00 1.23e+04 | | 37.916 37.916 37.92 37.92 37.916 000037.92 3.79e+01 | | 3567890 3567890 3.57e+06 3.57e+06 3567890 3.57e+06 3.57e+06 | | .9165 .9165 0.92 0.92 .9165 000000.92 9.16e-01 | +---------------------------------------------------------------------+ Left-aligned and right-aligned string display formats +-------------------------------+ | %-17s %17s | |-------------------------------| | AMC Concord AMC Concord | | AMC Pacer AMC Pacer | | AMC Spirit AMC Spirit | | Buick Century Buick Century | | Buick Opel Buick Opel | +-------------------------------+ ---------------------------------------------------------------------------- Setup . webuse census10 Describe the data . describe List some of the data . list in 1/8 Left-align the state variable . format state %-14s List the result . list in 1/8 Left-align region, a numeric variable with attached value label . format region %-8.0g List the result . list in 1/8 Insert commas in the variable pop . format pop %12.0gc List the result . list in 1/8 Vertically align the decimal points in medage . format medage %8.1f List the result . list in 1/8 ---------------------------------------------------------------------------- Setup . webuse fmtxmpl, clear List some of the data . list empid in 83/87 Attach leading zeros to empid values . format empid %05.0f List the result . list empid in 83/87 ---------------------------------------------------------------------------- Setup . webuse fmtxmpl2, clear Display the formats of the three date variables . format hiredate login logout Attach a date format to login and logout . format login logout %tcDDmonCCYY_HH:MM:SS.ss List the result . list login logout in 1/5 Attach a date format to the hiredate variable . format hiredate %td List the result . list hiredate in 1/5 Attach a different date format to the hiredate variable . format hiredate %tdDD/NN/CCYY List the result . list hiredate in 1/5 Display the current formats for all variables using describe . describe Display the formats for the variables whose display format is too long to show in the describe output . format ---------------------------------------------------------------------------- Setup . webuse census10, clear Attach a European format to the variables pop and medage . format pop %12,0gc (note the comma) . format medage %9,2gc List the result . list in 1/8 Remove the European format from variables pop and medage . format pop %12.0gc (back to period for the decimal point) . format medage %9.2gc Change the setting for the decimal point to comma . set dp comma Perform a one-way tabulation . tabulate region [fw=pop] Restore period as the setting for the decimal point . set dp period ---------------------------------------------------------------------------- Video example How to change the display format of a variable . coefplot dyn_reg, level(90) baselevels keep(pre4 pre3 pre2 current post1 post2) co > eflabels(pre4="-4" pre3="-3" pre2="-2" current="0" post1="1" post2="2") yline(0, l > color(black) lwidth(medium)) ylabel(-0.06(0.03)0.09, labsize(vsmall) angle(0) fmt( > %10.3f)) xlabel(, labsize(vsmall)) xtitle("政策时点", size(small)) ytitle("对薪酬 > 差距的边际效应", size(small)) addplot(line @b @at, lcolor(black) lwidth(medium)) c > iopts(lpattern(dash)recast(rcap) lcolor(gray*0.7) msize(medium)) msymbol(circle_ho > llow) mcolor(black) msize(large) scheme(s1mono) graphregion(fcolor(white) lcolor(w > hite)) plotregion(fcolor(white))legend(off) option fmt() not allowed r(198); . help fmt 这个报错了,你写代码的时候不要有换行符
最新发布
11-24
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值