人搜笔试编程题——树的层序遍历
来源:互联网 发布:路由器关闭了所有网络 编辑:程序博客网 时间: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())}
- 人搜笔试编程题——树的层序遍历
- 数据结构——树的遍历相关笔试题
- 树的层序遍历
- 树的层序遍历
- 数据结构——二叉树的建立和遍历(递归建树&层序遍历建树)
- 树的层遍历
- 【树】层序遍历
- 第十六题(树的层序遍历)
- 每日一题之二叉树的层序遍历
- 算法编程题1-二叉树的按层遍历(含换行)
- 层序遍历二叉树指定的某层
- 二叉树的层序遍历
- 二叉树的层序遍历
- 二叉树的层序遍历
- 二叉树的层序遍历
- 二叉树的层序遍历
- 二叉树的层序遍历
- 二叉树的层序遍历
- Kinect for Windows SDK开发入门(十八):Kinect Interaction交互控件
- WINCE6.0远程桌面显示修改
- C99中变长数组的内存分配策略
- 排列组合算法(非递归)
- (C语言)二叉树非递归遍历前序和中序(数据结构十四)
- 人搜笔试编程题——树的层序遍历
- 类的方法与属性(day05-13.10.17)
- Hibernate注解关系映射
- 全国省市数据库
- android使用ffmpeg的实例程序
- 程序 人生 历程
- C++文件操作写入和读取结构体类型
- 理解矩阵
- 黑马程序员 ---面向对象