#include <iostream>
#include <string>
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <stack>
using namespace std;
struct BinaryTreeNode{
int val;
BinaryTreeNode* left;
BinaryTreeNode* right;
BinaryTreeNode(int x):val(x),left(NULL),right(NULL){}
};
/// 8
/// / \
/// 6 10
/// / \ / \
/// 5 7 9 11
void sequencePrint(BinaryTreeNode* pRoot);
void tabPrint(BinaryTreeNode* pRoot);
void zhiPrint(BinaryTreeNode* pRoot);
void testBinaryPrint();
///前序顺序打印二叉树
/// 8 6 10 5 7 9 11
void sequencePrint(BinaryTreeNode* pRoot)
{
if(NULL == pRoot)
return;
queue<BinaryTreeNode*> nodes;
nodes.push(pRoot);
while(!nodes.empty())
{
BinaryTreeNode* pNode = nodes.front();
cout<<pNode->val<<" ";
if(NULL != pNode->left)
nodes.push(pNode->left);
if(NULL != pNode->right)
nodes.push(pNode->right);
nodes.pop();
}
cout<<endl;
}
///分行打印二叉树
/// 8
/// 6 10
/// 5 7 9 11
void tabPrint(BinaryTreeNode* pRoot)
{
if(NULL == pRoot)
return;
queue<BinaryTreeNode*> node;
node.push(pRoot);
int nextLevel=0,toBeprinted=1;
while(!node.empty())
{
BinaryTreeNode* pNode = node.front();
cout<<pNode->val<<" ";
if(NULL != pNode->left)
{
node.push(pNode->left);
nextLevel++;
}
if(NULL != pNode->right)
{
node.push(pNode->right);
nextLevel++;
}
node.pop();
toBeprinted--;
if(0 == toBeprinted)
{
cout<<endl;
toBeprinted = nextLevel;
nextLevel = 0;
}
}
cout<<endl;
}
/// 之字型打印二叉树
/// 8
/// 10 6
/// 5 7 9 11
void zhiPrint(BinaryTreeNode* pRoot)
{
stack<BinaryTreeNode*> nodes[2];
int current=0;///current = 0/1——>既可以控制栈,也可以控制行数的切换
nodes[current].push(pRoot);
while(!nodes[0].empty() || !nodes[1].empty())
{
BinaryTreeNode* pNode = nodes[current].top();
cout<<pNode->val<<" ";
nodes[current].pop();
if(0==current)
{
if(NULL != pNode->left)
nodes[1-current].push(pNode->left);
if(NULL != pNode->right)
nodes[1-current].push(pNode->right);
}
else
{
if(NULL != pNode->right)
nodes[1-current].push(pNode->right);
if(NULL != pNode->left)
nodes[1-current].push(pNode->left);
}
if(nodes[current].empty())
{
cout<<endl;
current = 1-current;
}
}
cout<<endl;
}
void testBinaryPrint()
{
BinaryTreeNode* pNode8 = new BinaryTreeNode(8);
BinaryTreeNode* pNode6 = new BinaryTreeNode(6);
BinaryTreeNode* pNode10 = new BinaryTreeNode(10);
BinaryTreeNode* pNode5 = new BinaryTreeNode(5);
BinaryTreeNode* pNode7 = new BinaryTreeNode(7);
BinaryTreeNode* pNode9 = new BinaryTreeNode(9);
BinaryTreeNode* pNode11 = new BinaryTreeNode(11);
pNode10->left = pNode9;
pNode10->right = pNode11;
pNode6->left = pNode5;
pNode6->right = pNode7;
pNode8->left = pNode6;
pNode8->right = pNode10;
cout<<"需要打印的二叉树:"<<endl;
cout<<" 8"<<endl;
cout<<" / \\"<<endl;
cout<<" 6 10"<<endl;
cout<<" / \\ / \\"<<endl;
cout<<"5 7 9 11"<<endl;
cout<<"前序顺序打印二叉树"<<endl;
sequencePrint(pNode8);
cout<<"分层分行打印二叉树"<<endl;
tabPrint(pNode8);
cout<<"之字形打印二叉树"<<endl;
zhiPrint(pNode8);
}
int main()
{
///测试打印二叉树
testBinaryPrint();
return 0;
}
打印二叉树——顺序、分层、之字形
最新推荐文章于 2022-03-25 12:49:46 发布