例题6-7 树的层次遍历

Trees on the level

Trees are fundamental in many branches of computer science (Pun definitely intended). Current stateof-the 
art parallel computers such as Thinking Machines’ CM-5 are based on fat trees. Quad- and 
octal-trees are fundamental to many algorithms in computer graphics. 
This problem involves building and traversing binary trees. 
Given a sequence of binary trees, you are to write a program 
that prints a level-order traversal of each tree. In this 
problem each node of a binary tree contains a positive integer 
and all binary trees have have fewer than 256 nodes. 
In a level-order traversal of a tree, the data in all nodes at 
a given level are printed in left-to-right order and all nodes at 
level k are printed before all nodes at level k + 1. 
For example, a level order traversal of the tree on the right 
is: 5, 4, 8, 11, 13, 4, 7, 2, 1. 
In this problem a binary tree is specified by a sequence 
of pairs ‘(n,s)’ where n is the value at the node whose path 
from the root is given by the string s. A path is given be 
a sequence of ‘L’s and ‘R’s where ‘L’ indicates a left branch and ‘R’ indicates a right branch. In the 
tree diagrammed above, the node containing 13 is specified by (13,RL), and the node containing 2 is 
specified by (2,LLR). The root node is specified by (5,) where the empty string indicates the path from 
the root to itself. A binary tree is considered to be completely specified if every node on all root-to-node 
paths in the tree is given a value exactly once. 
Input 
The input is a sequence of binary trees specified as described above. Each tree in a sequence consists 
of several pairs ‘(n,s)’ as described above separated by whitespace. The last entry in each tree is ‘()’. 
No whitespace appears between left and right parentheses. 
All nodes contain a positive integer. Every tree in the input will consist of at least one node and 
no more than 256 nodes. Input is terminated by end-of-file. 
Output 
For each completely specified binary tree in the input file, the level order traversal of that tree should 
be printed. If a tree is not completely specified, i.e., some node in the tree is NOT given a value or a 
node is given a value more than once, then the string ‘not complete’ should be printed. 
Sample Input 
(11,LL) (7,LLL) (8,R) 
(5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) () 
(3,L) (4,R) () 
Sample Output 
5 4 8 11 13 4 7 2 1 
not complete

题目链接:https://vjudge.net/problem/UVA-122

题意:

(11,LL)表示节点值为11,在第二层的左,第三层的左;
(5,)表示根节点;
总之,每一个L或者R代表从root到达该节点在每一层的转向,问,给一串这样的字符串,输出二叉树层序遍历的结果,
如果输入重复或者节点的val为0则表示输出错误“not complete”.

题解:

根据输入构造二叉树,然后用queue层序遍历输出即可。
(1)根据输入创建二叉树,技巧:sscanf(&s[1], "%d", &v),从数组中读取数字,strchr(s, ‘,‘)+1获取数字后的字符串最后一个‘)‘在处理时忽略;
(2)指针实现时,记得deletenode,root要先newnode;
(3)数组实现时,各节点按顺序存放,通过lf[maxn]和rt[maxn]数组确定左右节点;
(4)注意,已经有值的节点重复赋值要另flag = false,以及层序遍历时出现未赋值节点也要flag = false.

分析:

1。在输入方面,直接开了一个bool read_input()函数,这样在输入EOF时,就返回false,所以可以在main函数里直接这样写:while(read_input()){...}。

2。在这个read_input 函数里面,用到了sscanf (&s[1]),这样就把字符串从位置1开始的字符串后面读取整数!,后面又用到了strchr(s,‘,‘)把逗号后面的字符串提取出来。

3。在结构体node里面,用了一个构造函数,不仅把have_value这个关键变量初始化为false,并且把一个node 里面的left,right也初始化到NULL,在前面学字典树时,就没这样做,而是new node后再用循环初始化NULL,这里直接用构造函数初始化,就感觉比较巧妙了。

3。遍历二叉树时用了bfs+队列,先判断left,在判断right,这样就保证了输出顺序的正确性,

4。最后释放内存用到了递归释放内存,类似于字典树。

指针实现代码

:

//#include <bits/stdc++.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<string>
#include<stack>
#include<queue>
#include<iostream>
#define INF 0xffffffff
using namespace std;
typedef long long ll;

const int maxn = 300;

char s[maxn];
bool failed;
vector<int> a; 

struct Node{
    bool have_value;
    int v;
    Node *left, *right;
    Node():have_value(false), left(NULL), right(NULL){}
};
Node* root;

Node* newnode(){
    return new Node();
}

void addnode(int v, char* s){
    int n = strlen(s);
    Node *u = root;
    for(int i=0; i<n; i++){
        if(s[i] == ‘L‘){
            if(u->left == NULL) u->left = newnode();
            u = u->left;
        }
        else if(s[i] == ‘R‘){
            if(u->right == NULL) u->right = newnode();
            u = u->right;
        }
    }
    if(u->have_value) failed = true;
    u->v = v;
    u->have_value = true;
}

void remove_tree(Node* u){
    if(u == NULL) return;
    remove_tree(u->left);
    remove_tree(u->right);
    delete u;
}

bool read_input(){
    failed = false;
    remove_tree(root);
    root = newnode();
    for(;;){
        if(scanf("%s", s) != 1) return false;
        if(!strcmp(s, "()")) break;
        int v;
        sscanf(&s[1], "%d", &v);
        addnode(v, strchr(s, ‘,‘)+1);
    }
    return true;
}

bool bfs(vector<int>& ans){
    queue<Node*> q;
    ans.clear();
    q.push(root);
    while(!q.empty()){
        Node *u = q.front();
        q.pop();
        if(!u->have_value) return false;
        ans.push_back(u->v);
        if(u->left != NULL) q.push(u->left);
        if(u->right != NULL) q.push(u->right);
    }
    return true;
}

int main(){
    while(read_input()){
        if(bfs(a) && !failed){
            for(int i=0; i<a.size(); i++){
                if(i >0) printf(" ");
                printf("%d", a[i]);
            }
            printf("\n");
        }
        else{
            printf("not complete\n");
        }
    }
    return 0;
}

数组实现代码

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<string>
#include<stack>
#include<queue>
#include<iostream>
using namespace std;
typedef long long ll;
const int maxn=300;
const int root=1;
int lf[maxn];
int rt[maxn];
bool hv[maxn];
int val[maxn];
vector<int> ans;
bool flag;
int cnt;
void newtree()
{
    cnt=root;
    lf[root]=rt[root]=0;
    hv[root]=false;
}
int newnode()
{
    int u=++cnt;
    lf[u]=rt[u]=0;
    hv[u]=false;
    return u;

}
void addnode(int v,char *s)
{
    int n=strlen(s);
    int u=root;
    for(int i=0; i<n; i++)
    {
        if(s[i]==‘L‘)
        {
            if(lf[u]==0) lf[u]=newnode();//节点不存在,建立新节点
            u=lf[u];//往左走
        }
        else if(s[i]==‘R‘)
        {
            if(rt[u]==0) rt[u]=newnode();
            u=rt[u];
        }//忽略其他情况 即最后那个多余的右括号

    }
    if(hv[u]) flag=false;//have_value 本身已经有值
    val[u]=v;
    hv[u]=true;
}
bool input()
{
    newtree();
    flag=true;
    char s[30];
    for(;;)
    {
        if(scanf("%s",s)!=1) return false;//输入格式不正确
        if(!strcmp(s,"()")) break;//输入结束
        int v;
        //(11,LL) s[1]指 11,LL)
        sscanf(&s[1],"%d",&v);//读入节点值
        //保存后面的 (11,LL) 保存s[1]保存LL)
        //strchr返回的是从左往右 第一个字符”,“的指针
        addnode(v,strchr(s,‘,‘)+1);//添加节点

    }
    return true;
}
    bool bfs() //宽度优先遍历
    {
        ans.clear();
        queue<int> q;
        q.push(root);
        while(!q.empty())
        {
            int u=q.front();
            q.pop();
            if(hv[u]==false) return false;
            ans.push_back(val[u]);
            if(lf[u]!=0) q.push(lf[u]);
            if(rt[u]!=0) q.push(rt[u]);

        }
        return true;
    }
    int main()
    {
       while(input()){
        if(bfs()&&flag){
            for(int i=0;i<ans.size();i++)
            {
                if(i>0) printf(" ");
                printf("%d",ans[i]);
            }
            printf("\n");
        }
        else printf("not complete\n");
       }

    }

总结:

本题是训练二叉树的一道好题。首先要解决读数据问题,根据题意,当输入为“()”时,结束该组数据读入,当没有字符串时,整个输入结束。因此可以专门编写一个readin()函数,类型设置为bool型,遇到第一种情况时返回true,遇到第二种情况返回false,主程序中只要发现readin返回false时就break,结束整个大循环。

接下来要建立二叉树,首先为二叉树编写一个结构体,然后根据字符串的输入情况来建树,如果是‘L’就往左走,走不动时建一颗新树,同样的方法处理右子树,最后读入结点值。由于输入可能有误,因此用一个全局变量failed来记录是否有输入错误的情况出现,如果在建树过程中发现该结点已经被赋过值,那么全局变量failed变为true。

最后开始BFS找结点值,此时可能出现有结点没有结点值的情况,因此要把bfs定义为bool型,只要出现这种非法情况,返回false。最后便不难根据情况进行输出了。

时间: 2024-08-10 14:57:35

例题6-7 树的层次遍历的相关文章

紫书例题6-7 树的层次遍历

纯小白也能看懂的代码,一起努力 6.3.2 二叉树的层次遍历 例题6-7 树的层次遍历(Trees on the level, Duke 1993, UVa 122) 输入一棵二叉树,你的任务是按从上到下.从左到右的顺序输出各个结点的值.每个结点都按照从根结点到它的移动序列给出(L表示左,R表示右).在输入中,每个结点的左括号和右括号之间没有空格,相邻结点之间用一个空格隔开.每棵树的输入用一对空括号"()"结束(这对括号本身不代表一个结点),如图6-3所示 注意,如果从根到某个叶结点的

数据结构:树的BFS,树的层次遍历! 按先序遍历创建一棵树,然后以层次遍历输出。

按先序遍历创建一棵树,以层次遍历输出 样例输入 A B # D # # C E # # F # # 样例输出 LevelOrder: A B C D E F 代码: #include <iostream> #include <queue> using namespace std; struct node { //表示一个树上的节点 char ch; node *left, *right; }; node* creat() { //以递归的方式构造一棵二叉树 node *root =

树的层次遍历(Java代码实现)

与树的前中后序遍历的DFS思想不同,层次遍历用到的是BFS思想.一般DFS用递归去实现(也可以用栈实现),BFS需要用队列去实现. 层次遍历的步骤是: 1.对于不为空的结点,先把该结点加入到队列中 2.从队中拿出结点,如果该结点的左右结点不为空,就分别把左右结点加入到队列中 3.重复以上操作直到队列为空 1 public class Solution{ 2 class TreeNode { 3 int val; 4 TreeNode left; 5 TreeNode right; 6 TreeN

树的层次遍历(Trees on the level,UVA 122)

题目描述: 题目思路: 1.用结构链表来建树 2.用队列来实现层次遍历,当遍历到根节点时,将其子节点压入队列 #include <iostream> #include <cstdlib> #include <cstring> #include <vector> #include <queue> using namespace std; //树结点 struct Node{ int v ; Node* left,*right ; int have_

1127 ZigZagging on a Tree (30 分)树的层次遍历

1127 ZigZagging on a Tree (30 分) Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences. And it is a simple standard routine to pr

树——通用树的层次遍历

1,为何及如何按层次遍历通用树中的每一个数据元素? 1,通用树结构是一种容器类型的树结构,其用来装数据元素,所以应该提供一种方法来遍历树中的每一个数据结构: 2,往下分析: 2,当前的事实: 1,树是非线性的数据结构,树的结点没有固定的编号方式: 1,也就不能像链表一样统一编号来访问: 3,新的需求: 1,为通用树结构提供新的方法,快速遍历每一个结点: 4,设计思路(游标): 1,在树中定义一个游标(GTreeNode<T>*): 2,遍历开始前将游标指向根结点(root()): 3,获取游标

例题6-7 树的层次遍历 UVa122

1.题目描述:点击打开链接 2.解题思路:本题是训练二叉树的一道好题.首先要解决读数据问题,根据题意,当输入为"()"时,结束该组数据读入,当没有字符串时,整个输入结束.因此可以专门编写一个readin()函数,类型设置为bool型,遇到第一种情况时返回true,遇到第二种情况返回false,主程序中只要发现readin返回false时就break,结束整个大循环. 接下来要建立二叉树,首先为二叉树编写一个结构体,然后根据字符串的输入情况来建树,如果是'L'就往左走,走不动时建一颗新树

uva-122 树的层次遍历

题意概要:输入二叉树的每一个节点的信息,建树完毕后,按照层次顺序遍历这棵树,然后将每一个节点的权值给输出来! 注意:如果从根到某个叶节点的路径上有的节点没有在输入中给出或者给出超过一次, 应该输出"not complete".节点数不超过256个! 代码如下:(代码中有详细的注释!)此份代码用时为 9ms ! #include<iostream> #include<cstdio> #include<vector> #include<queue&

Uva 122 树的层次遍历 Trees on the level lrj白书 p149

是否可以把树上结点的编号,然后把二叉树存储在数组中呢?很遗憾如果结点在一条链上,那将是2^256个结点 所以需要采用动态结构 首先要读取结点,建立二叉树addnode()+read_input()承担这样的工作 然后遍历二叉树,读取结点编号输出bfs() 这道题有内存池应用的背景 附链接  http://blog.csdn.net/shawngucas/article/details/6574863 #include <cstdio> #include <cstring> #inc