#include <iostream>
using namespace std;
typedef struct _BinaryTree{
char ch;
_BinaryTree *pLeft;
_BinaryTree *pRight;
}BTreeNode;
//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...
BTreeNode *g_pRoot = NULL;
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;
}
动态创建二叉树
最新推荐文章于 2022-10-03 19:37:59 发布