#include<iostream> #include<stdlib.h> #include<deque> //插入标准库中的头文件 using namespace std; typedef struct treenode { char data; treenode *right; treenode *left; }*Node; //创建二叉树 void creat_tree(treenode *&rt) { char ch; ch = getchar(); if ('#' == ch) { rt = NULL; } else { rt = new treenode; rt->data = ch; creat_tree(rt->left); //构造左子树 creat_tree(rt->right); //构造右子树 } } //层次遍历 void gradation(treenode *&root) { //在这里采用层次遍历的方法 deque <Node> c; //定义一个空的队列 c.push_back(root); while (!c.empty()) { //如果队列不为空 Node temp = c.front(); //返回队列的第一个元素 if (temp) { //如果是非空结点 cout << temp->data << " "; c.pop_front(); //出队列 c.push_back(temp->left); //左孩子 c.push_back(temp->right); //右孩子 } else { c.pop_front(); //出队列 } } } int main() { treenode *root = NULL; cout << "请输入二叉树,空值以#代表:" << endl; creat_tree(root); //创建二叉树 gradation(root); system("pause"); return 0; } /* ABD##E##C#F## */
C++二叉树层次输出
猜你喜欢
转载自blog.csdn.net/coolsunxu/article/details/80357385
今日推荐
周排行