C++二叉树翻转

#include <iostream>
using namespace std;

template<typename Type>
struct Node
{
    Type data;
    Node *left;
    Node *right;
    Node(Type d = Type()) :data(d), left(NULL), right(NULL){}
};
template<typename Type>
class MyTree
{
public:
    MyTree(const char *str)
    {
        root = NULL;
        Init(root,str);
    }
private:
    void Init(Node<Type> *&t,const  char *& str)//初始化二叉树。
    {
        if (*str == '#')
        {
            t = NULL;
            return;
        }
        else
        {
            t = new Node<Type>(*str);
            Init(t->left,++str);
            Init(t->right, ++str);
        }
    }
public:
    void Reversed()//翻转二叉树。
    {
        Reversed(root);
    }
private:
    void Reversed(Node<Type> *&t)
    {
        if (t == NULL)return;
        else
        {
            Reversed(t->left);
            Reversed(t->right);
            Node<Type> *tmp = t->right;
            t->right = t->left;
            t->left = tmp;
        }
    }
public:
    void Show()
    {
        Show(root);
    }
private:
    void Show(Node<Type> *t)
    {
        if (t == NULL)
        {
            return;
        }
        cout << t->data << "  ";
        Show(t->left);
        Show(t->right);
    }
private:
    Node<Type> *root;
};
int main()
{
    MyTree<char> mt("abc##d##ef##g##");
    mt.Reversed();
    mt.Show();
    return 0;
}

你可能感兴趣的:(C++/C,数据结构)