// main.cpp
// BinaryTree
#include <iostream>
using namespace std;
typedef struct _BinaryTree{
char ch;
_BinaryTree *pLeft;
_BinaryTree *pRight;
}BTreeNode;
BTreeNode *g_pRoot = NULL;
//create 先序动态创建二叉树
void CreateBitnaryTree(BTreeNode **pNode)
{
char ch;
cin>>ch;
if(ch == '#')
{
return ;
}
if(NULL == *pNode)
{
*pNode = new BTreeNode;
(*pNode)->pLeft = NULL;
(*pNode)->pRight = NULL;
(*pNode)->ch = ch;
cout<<"输入'"<<ch<<"'左节点值:";
CreateBitnaryTree(&(*pNode)->pLeft);
cout<<"输入'"<<ch<<"'右节点值:";
CreateBitnaryTree(&(*pNode)->pRight);
}
}
void preorderTraversal(BTreeNode *pRoot)
{
if(NULL != pRoot)
{
if(pRoot->ch != '#')
cout<<pRoot->ch<<" ";
preorderTraversal(pRoot->pLeft);
preorderTraversal(pRoot->pRight);
}
}
void inorderTravesal(BTreeNode *pRoot)
{
if(NULL != pRoot)
{
inorderTravesal(pRoot->pLeft);
if(pRoot->ch != '#')
cout<<pRoot->ch<<" ";
inorderTravesal(pRoot->pRight);
}
}
void postorderTraversal(BTreeNode *pRoot)
{
if(NULL != pRoot)
{
postorderTraversal(pRoot->pLeft);
postorderTraversal(pRoot->pRight);
if(pRoot->ch != '#')
cout<<pRoot->ch<<" ";
}
}
int main(int argc, const char * argv[]) {
// insert code here...
cout<<"输入第一个节点('#'代表空):"<<endl;
CreateBitnaryTree(&g_pRoot);
cout<<"先序遍历:";
preorderTraversal(g_pRoot);
cout<<endl;
cout<<"中序遍历:";
inorderTravesal(g_pRoot);
cout<<endl;
cout<<"后序遍历:";
postorderTraversal(g_pRoot);
cout<<endl;
return 0;
}
二叉树动态链式创建以及遍历
最新推荐文章于 2026-05-17 05:15:43 发布
本文详细探讨了如何使用动态链式方式创建二叉树,并深入讲解了二叉树的前序、中序和后序遍历算法,通过实例解析帮助读者掌握二叉树操作的关键技巧。
3794

被折叠的 条评论
为什么被折叠?



