第七题:交换一棵二叉树中每个节点的左右子树,删除一棵二叉树中的所有叶子节点(递归操作)。

#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;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值