122 - Trees on the level

Background

Trees arefundamental in many branches of computer science. Current state-of-the artparallel computers such as Thinking Machines' CM-5 are based on fattrees. Quad- and octal-trees are fundamental to many algorithms in computergraphics.

This probleminvolves building and traversing binary trees.

The Problem

Given a sequenceof binary trees, you are to write a program that prints a level-order traversalof each tree. In this problem each node of a binary tree contains a positiveinteger and all binary trees have fewer than 256 nodes.

In a level-order traversalof a tree, the data in all nodes at a given level are printed in left-to-rightorder and all nodes at level k are printed before all nodes atlevel k+1.

For example, alevel order traversal of the tree

is: 5, 4, 8, 11,13, 4, 7, 2, 1.

In this problem abinary tree is specified by a sequence of pairs (n,s) where n isthe 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'swhere L indicates a left branch and R indicatesa right branch. In the tree diagrammed above, the node containing 13 isspecified by (13,RL), and the node containing 2 is specified by (2,LLR). Theroot node is specified by (5,) where the empty string indicates the path fromthe root to itself. A binary tree is considered to be completelyspecified if every node on all root-to-node paths in the tree is givena value exactly once.

The Input

The input is asequence of binary trees specified as described above. Each tree in a sequenceconsists of several pairs (n,s) as described above separated bywhitespace. The last entry in each tree is (). No whitespace appears betweenleft and right parentheses.

All nodes containa positive integer. Every tree in the input will consist of at least one nodeand no more than 256 nodes. Input is terminated by end-of-file.

The Output

For eachcompletely specified binary tree in the input file, the level order traversalof 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 thanonce, 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 21

not complete

代码:

方法一(排序判断):

#include<iostream>

#include<string>

#include<set>

#include<algorithm>

using namespacestd;

 

struct Node

{

    string v;

    string path;

};

 

Node nodes[300];//最多256个结点

set<string>p_set; //主要利用set查找快速的特点

 

int get_(string s)//找到逗号的下标,找不到返回 -1

{

    int i=0;

    for (i=0; i<s.length(); i++)

    {

        if (s[i]==',')

        {

            return i;

        }

    }

    return -1;

}

 

bool cmp(const Node& a, const Node& b)

{

    if (a.path.length()!=b.path.length())

    {

        returna.path.length()<b.path.length();//长度小的在前面

    }

    return a.path<b.path;//长度相同的字典序小的在前面

}

 

int main()

{

    int flag=1;

    int i=0,j;

string str;

    p_set.clear();//不要忘记清空

    while (cin >> str)

    {

        if (str!="()")

        {

            j=get_(str);

            if (true)

            {

                nodes[i].v=str.substr(1,j-1);//利用substr函数取出数字和路径

                nodes[i].path=str.substr(j+1,str.length()-j-2);

                if (p_set.find(nodes[i].path)!=p_set.end())

                {

                    flag=0;//某个节点给出超过一次

                }

                else

                {

                   p_set.insert(nodes[i].path);

                }

                i++;

            }

        }

        else//开始处理一组数据

        {

            if (flag==0)

            {

                cout << "notcomplete\n";//某个节点给出超过一次

            }

            else

            {

                sort(nodes, nodes+i, cmp);//按照编写的谓词排序,最关键

                p_set.clear();//清空路径字符串的集合

                if (nodes[0].path.length()==0)

                {

                   p_set.insert(nodes[0].path);

                    for (j=1; j<i; j++)

                    {

                        if(p_set.find(nodes[j].path.substr(0,nodes[j].path.length()-1))==p_set.end())

                        {

                            flag=0;

//从根到某个叶节点的路径上有的结点没有给出

                        }

                        else

                        {

                           p_set.insert(nodes[j].path);

                        }

                    }

                    if (flag==0)

                    {

                        cout << "notcomplete\n";

//从根到某个叶节点的路径上有的结点没有给出

                    }

                    else

                    {

                        for (j=0; j<i-1;j++)

                        {

                            cout <<nodes[j].v << " ";

                        }

                        cout <<nodes[j].v << endl;

                    }

                }

                else

                {

                    cout << "notcomplete\n";//没有根节点

                }

            }

            i=0;

            p_set.clear();//清空上一组数据

            flag=1;

        }

    }

    return 0;

}

方法二(数据结构):

#include<iostream>

#include<vector>//使用动态数组存储结点的值

#include<queue>//使用queue存储结点

#include<string>

using namespacestd;

 

struct Node//节点类型

{

    bool have_value;//是否被赋值过

    string v;//结点的值

Node* left, *right;

//二叉树是递归定义的,左右子节点的类型是“指向结点类型的指针”

    Node():have_value(false),left(NULL),right(NULL){} //构造函数

};

 

Node* root;//二叉树的根结点

bool flag=true;

vector<string>ans;

 

bool input();

voidaddnode(string num,string path);

voidremovetree(Node * u);

Node * newnode();

bool bfs();

 

int main()

{

    while(input())

    {

        if(flag)

        {

            if(bfs())

            {

                cout<<ans[0];

                for(inti=1;i<ans.size();i++)

                {

                    cout<<""<<ans[i];

                }

                cout<<endl;

            }

            else

            {

                cout<<"notcomplete\n";

            }

        }

        else

        {

            cout<<"notcomplete\n";

        }

        flag=true;

    }

    return 0;

}

 

bool input()

{

    removetree(root);

    root=newnode();

    string temp;

    while(cin>>temp)

    {

        if(temp!="()")

        {

            int i;

            for(i=0;i<temp.size();i++)

            {

                if(temp[i]==',')

                {

                    break;

                }

            }

            string n=temp.substr(1,i-1);

            strings=temp.substr(i+1,temp.size()-i-2);

            addnode(n,s);

        }

        else

        {

            return true;

        }

    }

    return false;

}

 

void removetree(Node*u)

{

    if(u == NULL)

    {

        return;//提前判断

    }

    removetree(u->left);//递归调用

    removetree(u->right);

    delete u;//调用U的析构函数并释放U节点本身的内存

}

 

Node* newnode()

//每次需要新的Node,都要执行构造函数,并将新Node的地址赋给变量

{

    return new Node();

}

 

voidaddnode(string num,string path)

{

    Node * u=root;

    for(int i=0;i<path.size();i++)

    {

        if(path[i]=='L')

        {

            if(u->left==NULL)

            {

                u->left=newnode();

            }

            u=u->left;

        }

        else if(path[i]=='R')

        {

            if(u->right==NULL)

            {

                u->right=newnode();

            }

            u=u->right;

        }

    }

    if(u->havevalue) //重复赋值则错误

    {

        flag=false;

    }

    u->n=num; //指向运算符

    u->havevalue=true; //表示已经赋值

}

 

bool bfs()//宽度优先搜索

{

    queue<Node*> q;//队列元素类型是结构体的地址

    ans.clear();//每组数据使用前都要清空

    q.push(root);//初始只有一个根结点

    while(!q.empty())

    {

        Node* u = q.front();

        q.pop();//去除掉已取出的节点

        if(!u->have_value)//如果没有被赋值,即结点没有给出

        {

            flag=false;

        }

        ans.push_back(u->v);//将结点的值放在动态数组中

        if(u->left != NULL)//将取出的节点的左右子节点放到队列中

        {

            q.push(u->left);

        }

        if(u->right != NULL)

        {

            q.push(u->right);

        }

    }

    return true;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值