您的位置:首页 > 其它

二叉树的建立以及三种遍历方式的递归、非递归的实现

2013-10-04 00:02 801 查看
#include <iostream>
#include <stack>
using namespace std;

char src[]="abd ceg f ";
int index=0;

typedef struct BinaryNode
{
char key;
struct BinaryNode* left;
struct BinaryNode* right;
}BinaryNode,*BinaryTree;

void createBinaryTree(BinaryTree& root)
{
if (src[index]==' ')
{
root=NULL;
index++;

}
else
{
root=new BinaryNode();
root->key=src[index++];
createBinaryTree(root->left);
createBinaryTree(root->right);
}

}

void preOrderRecursive(BinaryTree root)
{
if (root)
{
cout<<root->key<<" ";
preOrderRecursive(root->left);
preOrderRecursive(root->right);
}
}

void preOrderIterative(BinaryTree root)
{
stack<BinaryTree> nodes;

while(!nodes.empty()||root!=NULL)
{
while(root!=NULL)
{
cout<<root->key<<" ";
nodes.push(root);
root=root->left;
}
root=nodes.top();
nodes.pop();
root=root->right;

}

}

void inOrderRecursive(BinaryTree root)
{
if (root)
{
inOrderRecursive(root->left);
cout<<root->key<<" ";
inOrderRecursive(root->right);
}
}

void inOrderInterative(BinaryTree root)
{
stack<BinaryTree> nodes;
while(!nodes.empty()||root!=NULL)
{
while(root!=NULL)
{
nodes.push(root);
root=root->left;
}
root=nodes.top();
cout<<root->key<<" ";
nodes.pop();
root=root->right;
}
}

void postOrderRecursive(BinaryTree root)
{

if (root)
{
postOrderRecursive(root->left);
postOrderRecursive(root->right);
cout<<root->key<<" ";
}
}

void poseOrderIterative(BinaryTree root)
{
if (root==NULL)
{
return;
}
stack<BinaryTree> nodes;
BinaryTree pre=NULL;
BinaryTree cur=NULL;

nodes.push(root);
while(!nodes.empty())
{
cur=nodes.top();
if ((cur->left==NULL&&cur->right==NULL)||(pre!=NULL&&(pre==cur->left||pre==cur->right)))
{
cout<<cur->key<<" ";
pre=cur;
nodes.pop();
}
else
{
if (cur->right!=NULL)
{
nodes.push(cur->right);
}
if (cur->left!=NULL)
{
nodes.push(cur->left);
}

}

}

}
int main()
{
BinaryTree root=NULL;
createBinaryTree(root);
preOrderRecursive(root);
cout<<endl;
preOrderIterative(root);
cout<<endl;
inOrderRecursive(root);
cout<<endl;
inOrderInterative(root);
cout<<endl;
postOrderRecursive(root);
cout<<endl;
poseOrderIterative(root);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: