目录
前言
本人刷剑指offer的一些程序记录,头文件,主函数都齐全,可直接上机运行
一、题目
从上往下打印出⼆叉
树
的每个节点,同层节点从左⾄右打印。
二、程序
创建二叉树是使用先序创建二叉链表的方法
1.头文件
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
typedef struct TreeNode
{
char val;
TreeNode *lchild;
TreeNode *rchild;
}*BiTree;
2.类和主函数
class solution
{
public:
vector<char> PrintFromTopToBottom(BiTree T)
{
BiTree ft;
if(T==NULL) return result;
que.push(T);
while(!que.empty())
{
ft=que.front();
result.push_back(ft->val);
if(ft->lchild!=NULL) que.push(ft->lchild);
if(ft->rchild!=NULL) que.push(ft->rchild);
que.pop();
}
return result;
}
void CreateBiTree(BiTree &T)
{
char ch;
cin>>ch;
if(ch=='#') T=NULL;
else
{
T=new TreeNode;
T->val=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
private:
vector<char> result;
queue<BiTree> que;
};
int main()
{
BiTree T;
solution stu;
vector<char> vec;
cout<< "请输入 tree 建立二叉链表的序列:\n";
stu.CreateBiTree(T);
vec=stu.PrintFromTopToBottom(T);
cout<< "按层次打印的序列为:\n";
for(vector<char>::iterator itor=vec.begin();itor!=vec.end();++itor)
{
char val=*itor;
cout<<val<<" ";
}
}