人搜笔试编程题——树的层序遍历

来源:互联网 发布:路由器关闭了所有网络 编辑:程序博客网 时间:2024/06/06 07:38

原题目: 一颗树的节点定义格式如下:

struct  Node{

                 Node* parent;

                 Node* firstchild;

                 Node* sibling;                        

                          }

要求非递归遍历该树。

思路:采用队列存储,来遍历节点。

 

首先分析题目,树节点中,三个指针,分别指向父结点,第一个孩子结点(由其英文意思获知),以及兄弟结点。

且思路中的提醒中为借助队列存储,我们都知道,采用深度遍历的三种遍历方法进行非递归遍历时,一般都是借助于栈结构实现。由此,可知该题意在要求使用层序遍历该树,亦即广度优先遍历。

 

c++代码 实现如下:

//非递归层序遍历树#include<queue>using namespace std;struct Node{    Node* parent;    Node* firstchild;    Node* sibling;    int data;}int levelordertree(struct Node* root){     queue<struct Node*> tqueue;     struct Node* p;     if(root==null)  return 0;     do        {            if(root->sibling!=null)     //有兄弟结点              {                 tqueue.push(root);                 root=root->sibling;               }             else                       //无兄弟结点               {                    tqueue.push(root);                     p=tqueue.front();     //队首元素赋值于p                    tqueue.pop();                     cout<<p->data<<endl;                          if(p->firstchild!=null)  //有叶结点                     {                        root=p->firstchild;                     }                    else                     //无叶结点                     {                        while(!tqueue.empty()||root!=null)                          {                             p=tqueue.front();                             tqueue.pop();                             cout<<p->data<<endl;                             root=p->firstchild;                           }                      }                }         } while(!tqueue.empty()||root==null)}


班门弄斧,望各路大牛不吝赐教

 

第二种解法。

        将该树转化为一个二叉树,题中要求为遍历树,未说一定要层序遍历。那么我们在层序遍历该树转化后的二叉树。

        很明显,转化为二叉树以后,该题好做很多。我们可直接将结点理解成

 

struct  Node{         int data;          Node* parent;         Node*  lchild ;     //  firstchild         Node* rchild;        //  sibling}int  levelorderbintree(Node* root){     queue<Node*>  tqueue;                 if(root==null) return -1;               do {                    tqueue.push(root);                   if(root->lchild!=null) tqueue.push(root->lchild);                  if(root->rchild!=null) tqueue.push(root->rchild);                  root=tqueue.front(); tqueue.pop();                  cout<<root->data<<endl;                     }while(!tqueue.empty())}