从顶层开始逐层打印二叉树节点数据
10
/ \
6 14
/ \ / \
4 8 12 16
逐层打印的结果为 10 6 14 4 8 12 16
采用队列的方式 ,先把根节点存入队列,然后再出列,输出这个数据。如果有左子树,把左子树根节点入列,如果右子树不为空,把右子树的根节点入列,然后如果队列不为空,则出列。直到队列为空。
void print(TreeNode * root)
{
queue<TreeNode> tree; //声明一个树节点的队列
TreeNode tmp = NULL;
tree.push(root); //首先把根节点入列
while( ! tree.empty())
{
tmp = tree.front();
tree.pop();
(*visit)(tmp);
if(tmp->left != NULL)
{
tree.push(tmp->left);
}
if(tmp->right != NULL)
{
tree.push(tmp->right);
}
}
}
void visit(TreeNode *node)
{
printf("%d",node->data);
}
#include <iostream>
//#include <deque>
#include <queue>
using namespace std;
typedef struct BtreeNode
{
int data;
struct BtreeNode *left ,*right;
}node;
void create(node *&r ,int m)
{
if(r==NULL)
{
node *t =new node();
t->data = m;
t->left =NULL;
t->right =NULL;
r = t;
}
else
{
if(m>r->data)
{
create(r->right ,m);
}
if(m<r->data)
{
create(r->left ,m);
}
}
}
void print(node *r)
{
queue<node*>tmp;
tmp.push(r);
while(!tmp.empty())
{
node *p = tmp.front();
cout<<p->data<<endl;
tmp.pop();
if(p->left)
{
tmp.push(p->left);
}
if(p->right)
{
tmp.push(p->right);
}
}
}
jingxiang(node *&r)
{
if(!r)
{
return;
}
node *p = r;
p = r->left;
r->left = r->right;
r->right = p;
if(r->left)
{
jingxiang(r->left);
}
if(r->right)
{
jingxiang(r->right);
}
}
void main()
{
node *root=NULL;
create(root , 10);
create(root , 6);
create(root , 4);
create(root , 8);
create(root , 14);
create(root , 12);
create(root , 16);
print(root);
jingxiang(root);
print(root);
}