怎样从顶部开始逐层打印二叉树结点数据?
2011-09-26 15:02
351 查看
//怎样从顶部开始逐层打印二叉树结点数据?
#include <iostream>
#include "stdlib.h"
#include <string>
#include <list>
#include <queue>
using namespace std;
typedef struct node {
int value;
struct node *lchild;
struct node *rchild;
}Node,*Bintree;
queue<Node,list<Node> > q;
int i=0;
int mycount=3;
Bintree & createBintree(Bintree &p)
{
p = (Bintree)malloc(sizeof(Node));
p->value = ++i;
if (--mycount>=0) {
p->lchild = createBintree(p->lchild);
p->rchild = createBintree(p->rchild);
}
else
{
p->lchild =NULL;
p->rchild =NULL;
}
return p;
}
void BFSTraverse(Bintree T)
{
Node a;
if(T)q.push(*T);
while(!q.empty())
{
a=q.front();
cout<<a.value<<" ";
q.pop();
if(a.lchild)q.push(*a.lchild);
if(a.rchild)q.push(*a.rchild);
}
}
void display_tree(Bintree tree) {
if(tree){
display_tree(tree->lchild);
cout<<tree->value<<" ";
display_tree(tree->rchild);
}
}
int main() {
static Bintree tree;
createBintree(tree);
cout<<endl<<"中序遍历二叉树";
display_tree(tree);
cout<<endl<<"层序遍历二叉树";
BFSTraverse(tree);
return 0;
}
相关文章推荐
- 微软等数据结构+算法面试100题(4)--怎样从顶部开始逐层打印二叉树结点数据?请编程
- 怎样从顶部开始逐层打印二叉树结点数据?蛋疼解法
- 从顶部开始逐层打印二叉树结点数据
- 6、怎样从顶部开始逐层打印二叉树
- 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
- 给定一棵二叉树,每个结点包含一个值。打印出所有满足以下条件的路径: 路径上结点的值加起来等于给定的一个值。注意:这些路径不必从根结点开始。
- 从底层逐层的开始打印出二叉树的节点数据
- 题目:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶结点所经过的结点形成一条路径。
- 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
- java 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
- 数据结构(C语言实现) - 二叉树的基本操作(建立,遍历,结点数,叶子结点数,高度,按树状打印,输出叶子结点等)
- 从顶层开始逐层打印二叉树节点数据
- 给定一棵二叉树,每个结点包含一个值。打印出所有满足以下条件的路径: 路径上结点的值加起来等于给定的一个值。注意:这些路径不必从根结点开始。
- 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径
- 剑指offer 打印出二叉树中结点值的和为输入整数的所有路径。
- 数据结构——交换二叉树中所有结点的左右子树(所有结点换位置)
- 怎样按层次打印二叉树
- 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
- 数据结构之打印二叉树所有(根结点起)路径—整理严蔚敏数据结构
- 打印出二叉树中结点值的和为输入整数的所有路径