#include <iostream>
#include <assert.h>
#include <queue>
using namespace std;
struct BiTreeNode{
int m_nValue;
BiTreeNode* m_pLeft;
BiTreeNode* m_pRight;
} ;
void createTree(BiTreeNode* &root,int value){
if(root==NULL){
root=new BiTreeNode;
root->m_nValue=value;
root->m_pLeft=NULL;
root->m_pRight=NULL;
return;
}
if(value<root->m_nValue)
createTree(root->m_pLeft,value);
else
createTree(root->m_pRight,value);
}
void printInOrder(BiTreeNode *root){
if(root==NULL)
return;
printInOrder(root->m_pLeft);
cout<<root->m_nValue<<" ";
printInOrder(root->m_pRight);
}
void printInLevel(BiTreeNode *root){
if(root==NULL)
return;
queue<BiTreeNode*> que;
que.push(root);
while(!que.empty()){
BiTreeNode* pNode=que.front();
cout<<pNode->m_nValue<<" ";
que.pop();
if(pNode->m_pLeft!=NULL)
que.push(pNode->m_pLeft);
if(pNode->m_pRight!=NULL)
que.push(pNode->m_pRight);
}
}
void main(){
BiTreeNode* root=NULL;
createTree(root,5);
createTree(root,3);
createTree(root,4);
createTree(root,7);
createTree(root,2);
createTree(root,6);
createTree(root,1);
printInOrder(root);
cout<<endl;
printInLevel(root);
cout<<endl;
system("pause");
}
层次遍历二叉树
最新推荐文章于 2024-05-17 21:51:18 发布