用C++实现了树的前序遍历,中序遍历,后序遍历以及层次遍历。分别用迭代与递归进行实现。(能够直接运行)代码如下:
//============================================================================
// Name : binaryTree.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <stdlib.h>
#include <stack>
#include<queue>
using namespace std;
class BTree{
public:
int value;
int id;
bool visited;
BTree* lChild;
BTree* rChild;
};
BTree* btrees[100];
int size;
void buildTree(){
cout<<"building a binary tree with "<<size<<" nodes"<<endl;
int i;
for(i=1;i<=size;i++){
btrees[i]=new BTree;
btrees[i]->value = rand()%100;
btrees[i]->id = i;
btrees[i]->visited = false;
}
int lchild,rchild;
for(i=1;i<=size/2;i++){
lchild=i*2;rchild=i*2+1;
if(rchild<=size)
btrees[i]->rChild = btrees[rchild];
btrees[i]->lChild = btrees[lchild];
}
}
void visit(BTree * tree){
if(NULL!=tree){
cout<<"visit node"<<tree->id<<" value is "<<tree->value<<endl;
tree->visited= true;
}
}
void preOrder(BTree *root){
cout<<"preOrder"<<endl;
if(NULL!=root){
visit(root);
preOrder(root->lChild);
preOrder(root->rChild);
}
}
void preOrderIter(BTree *root){
cout<<"preOrderIter"<<endl;
stack<BTree *> s;
// s.push(root);
while(!s.empty()||root!=NULL){
if(root==NULL){
root=s.top();
s.pop();
root=root->rChild;
}else{
visit(root);
s.push(root);
root= root->lChild;
}
}
}
void inOrder(BTree *root){
cout<<"inorder"<<endl;
if(NULL!=root){
inOrder(root->lChild);
visit(root);
inOrder(root->rChild);
}
}
void inOrderIter(BTree *root){
cout<<"inOrderIter"<<endl;
stack<BTree *> s;
while(NULL!=root||!s.empty()){
if(root!=NULL){
s.push(root);
root=root->lChild;
}else{
root = s.top();
s.pop();
visit(root);
root=root->rChild;
}
}
}
void postOrder(BTree *root){
cout<<"postOrder"<<endl;
if(NULL!=root){
postOrder(root->lChild);
postOrder(root->rChild);
visit(root);
}
}
void postOrderIter(BTree *root){
cout<<"postOrderIter"<<endl;
stack<BTree*> s;
s.push(root);
while(root!=NULL&&!s.empty()){
root=s.top();
if((root->lChild==NULL&&root->rChild==NULL)||(root->lChild->visited==true&&root->rChild->visited==true)){
s.pop();
visit(root);
}else{
if(root->rChild)
s.push(root->rChild);
if(root->lChild!=NULL)
s.push(root->lChild);
}
}
}
void levelOrder(BTree* root){
cout<<"level order"<<endl;
queue<BTree*> q;
q.push(root);
while(root!=NULL&&!q.empty()){
root=q.front();
q.pop();
visit(root);
if(root->lChild)
q.push(root->lChild);
if(root->rChild)
q.push(root->rChild);
}
}
int main() {
// cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
cout<<"input size of tree: ";
cin>>size;cout<<endl;
buildTree();
// preOrder(btrees[1]);
// inOrder(btrees[1]);
// postOrder(btrees[1]);
// preOrderIter(btrees[1]);
// inOrderIter(btrees[1]);
// postOrderIter(btrees[1]);
levelOrder(btrees[1]);
return 0;
}