#include<iostream>
#include<cstdlib>
using namespace std;
template<class T>
class BinaryTreeNode{
public:
T data;
BinaryTreeNode<T> *leftchild;
BinaryTreeNode<T> *rightchild;
BinaryTreeNode(T data = 0){
this->data = data;
this->leftchild = rightchild = NULL;
}
};
template<class T>
class BinaryTree{
private:
BinaryTreeNode<T> *root;
public:
BinaryTree(){
this->root = NULL;
}
void visit(BinaryTreeNode<T> *p){
cout << p->data << " ";
}
BinaryTreeNode<T>* Create(BinaryTreeNode<T> *root); //创建二叉树
void preOrder(BinaryTreeNode<T> *root); //先序遍历二叉树
void exchange(BinaryTreeNode<T> *root); //交换左右子树
void deletelea(BinaryTreeNode<T> *root,BinaryTreeNode<T> *pre); //删除叶子结点
};
template<class T>
BinaryTreeNode<T>* BinaryTree<T> :: Create(BinaryTreeNode<T> *root){
char x;
cin >> x;
if(x == '0')
return NULL;
else{
root = new BinaryTreeNode<T>(x);
root->leftchild = Create(root->leftchild);
root->rightchild = Create(root->rightchild);
return root;
}
}
template<class T>
void BinaryTree<T> :: preOrder(BinaryTreeNode<T> *root){
if(root != NULL){
visit(root);
preOrder(root->leftchild);
preOrder(root->rightchild);
}
}
template<class T>
void BinaryTree<T> :: exchange(BinaryTreeNode<T> *root){
BinaryTreeNode<T> *temp;
if(root != NULL){
temp = root->leftchild;
root->leftchild = root->rightchild;
root->rightchild = temp;
exchange(root->leftchild);
exchange(root->rightchild);
}
}
template<class T>
void BinaryTree<T> :: deletelea(BinaryTreeNode<T> *root,BinaryTreeNode<T> *pre){
if(root!= NULL){
if(root->leftchild == NULL&&root->rightchild == NULL){
if(pre != NULL){
if(root == pre->leftchild)
pre->leftchild = NULL;
if(root == pre->rightchild)
pre->rightchild = NULL;
free(root);
}
}
else{
pre = root;
deletelea(root->leftchild,pre);
deletelea(root->rightchild,pre);
}
}
}
int main(){
BinaryTreeNode<char> *root;
BinaryTreeNode<char> *pre = NULL;
BinaryTree<char> *t;
root = t->Create(root);
t->preOrder(root);
/*cout << endl << "交换后的二叉树先序序列为:" << endl;
t->exchange(root);
t->preOrder(root);*/
cout << endl << "删除叶子结点后的二叉树先序序列为:" << endl;
t->deletelea(root,pre);
t->preOrder(root);
return 0;
}