二叉树的创建,遍历与销毁
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct TreeNode{
char val;//数据域
TreeNode* lchild;//左子树
TreeNode* rchild;//右子树
};
class BiTree{
private:
TreeNode* root;//根节点
public:
BiTree(){
root=create(root);//再写一个创造二叉树的函数
}
~BiTree(){
release(root);//写一个销毁二叉树的函数
}
TreeNode* getRoot(){
return root;
}
void release(TreeNode* bt){
if(bt==NULL) return;
release(bt->lchild);
release(bt->rchild);
cout<<"delete"<<" "<<bt->val<<endl;
delete bt;
}
TreeNode* create(TreeNode* bt){
char ch;
cin>>ch;
if(ch=='#') return NULL;
else{
//前序遍历构造二叉树
bt=new TreeNode;
bt->val=ch;
bt->lchild=create(bt->lchild);
bt->rchild=create(bt->rchild);
}
}
void preOrder(TreeNode* bt){
if(bt==NULL) return;
else{
cout<<bt->val;//中
preOrder(bt->lchild);//左
preOrder(bt->rchild);//右
}
}
void inOrder(TreeNode* bt){
if(bt==NULL) return;
else{
inOrder(bt->lchild);//左
cout<<bt->val;//中
inOrder(bt->rchild);//右
}
}
void postOrder(TreeNode* bt){
if(bt==NULL) return;
else{
postOrder(bt->lchild);//左
postOrder(bt->rchild);//右
cout<<bt->val;//中
}
}
void levelOrder(){
queue<TreeNode*> q;
if(root!=NULL) q.push(root);//先入队头结点
while(!q.empty()){
TreeNode* node=q.front();
q.pop();
cout<<node->val;
if(node->lchild) q.push(node->lchild);//左右子结点分别入队
if(node->rchild) q.push(node->rchild);
}
}
};
int main() {
BiTree tree;//会调用构造函数,将字符串读入
tree.preOrder(tree.getRoot());//前序遍历,递归代码为中左右
cout<<endl;
tree.inOrder(tree.getRoot());//中序遍历,递归代码为左中右
cout<<endl;
tree.postOrder(tree.getRoot());//后序遍历,递归代码为左右中
cout<<endl;
tree.levelOrder();//利用队列实现层序遍历
cout<<endl;
return 0;
//结束,调用析构函数
}
不足之处欢迎批评与指正!
标签:lchild,遍历,TreeNode,bt,销毁,二叉树,return,rchild,root From: https://blog.csdn.net/2301_78759802/article/details/136891331