二叉树的层次遍历(f m)
来源:互联网 发布:c语言的运用 编辑:程序博客网 时间:2024/05/21 10:36
基础二叉树第层次遍历
首先呢,二叉树的构造就不用说啦。。。都知道,一种告诉你类满二叉树,还有一种呢。。就是两个遍历构造。。。这些已经都很熟悉了。。
看看题
Problem Description
已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。
Input
输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。
Output
每组输出这颗二叉树的层次遍历。
Example Input
2
abc
bac
abdec
dbeac
Example Output
abc
abcde
很容易理解,我们来看看代码
#include <stdio.h>#include <string.h>#include <stdlib.h>struct node{ char data; struct node *l,*r;};struct node *creat(int n,char *str1,char *str2){ struct node *root; int i; if(n==0) return NULL; root = new node; root -> data = str1[0]; for(i=0;i<n;i++) { if(str2[i] == str1[0]) break; } root -> l = creat(i,str1 + 1,str2); root -> r = creat(n-1-i,str1 + i + 1,str2 + i + 1); return root; } int p(struct node *root) { struct node *q[1100],*p; int s = 0,e = 0; if(!root) return 0; q[e++] = root; while(s<e) { p = q[s++]; printf("%c",p->data); if(p->l) q[e++] = p -> l; if(p -> r) q[e++] = p -> r; } }int main(){ int n; scanf("%d",&n); while(n--) { char s1[100010],s2[100010]; scanf("%s",s1); scanf("%s",s2); int m = strlen(s1); struct node *root = creat(m,s1,s2); p(root); printf("\n"); }}
只需要记住,用队列来记录这个节点
(1)根节点入队列
(2)输出队列第一个,如果有左孩子,左孩子入队列,如果有右孩子,右孩子入队列。
(3)重复步骤(2),直到队列为空
0 0
- 二叉树的层次遍历(f m)
- Lintcode(M) 二叉树的层次遍历
- 二叉树的层次遍历(打印)
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历!!!
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- Seamless cloning泊松克隆
- Nginx服务器安装
- Trip
- css编码规范(二)
- 微信小程序获取系统日期和时间 —— 微信小程序教程系列(17)
- 二叉树的层次遍历(f m)
- 安卓-控制EditText的光标的位置
- Java中的集合框架概述
- mysql修改字符集
- macbook pro (Retina 2015年中)双系统安装
- 49. spring boot日志升级篇—理论【从零开始学Spring Boot】
- SQL基础知识整理
- C# 设置ie代理
- shell脚本中一些特殊符号