基于二叉链表的二叉树的遍历
#include <iostream>
using namespace std;
typedef struct TreeNode{
char val;
TreeNode* left;
TreeNode* right;
TreeNode():val(0),left(nullptr),right(nullptr){};
TreeNode(int x):val(x),left(nullptr),right(nullptr){};
}TreeNode,*BiTree;
BiTree PreInsertBiTree(){
char x;
cin>>x;
if(x == '0') return nullptr;
TreeNode* root = new TreeNode (x);
root->left = PreInsertBiTree();
root->right = PreInsertBiTree();
return root;
}
void PreOrder(BiTree B){
if(B == nullptr || B->val == '0') return ;
cout<<B->val;
PreOrder(B->left);
PreOrder(B->right);
}
void InOrder(BiTree B){
if(B == nullptr || B->val == '0') return;
InOrder(B->left);
cout<<B->val;
InOrder(B->right);
}
void PostOrder(BiTree B){
if(B == nullptr || B->val == '0') return ;
PostOrder(B->left);
PostOrder(B->right);
cout<<B->val;
}
void DeleteTree(BiTree B){
if(B == nullptr) return ;
DeleteTree(B->left);
DeleteTree(B->right);
delete B;
}
int main(){
BiTree B;
do {
B = PreInsertBiTree();
if (B != nullptr) { // 确保B不是空的
PreOrder(B);
cout << endl;
InOrder(B);
cout << endl;
PostOrder(B);
cout << endl;
}
DeleteTree(B); // 删除旧的二叉树
} while (B != nullptr && B->val != '0'); // 修改循环条件
return 0;
}