C++二叉树的建立、前序、中序、后序遍历

最近在LintCode上练习算法,感觉对数据结构的体用Python或者Java写起来都很费劲,像二叉树这种数据结构,Python是Java都用对象进行封装实现的,感觉有点浪费,还是用C++写起来比较顺手,不过好久不用C++,好多都忘 了,所以在这里记录一下,免得再忘 了,还不知道去哪里找。

二叉树是数据结构里最觉的一种了,重要性不言而喻。

#include<iostream>
using namespace std;

struct TreeNode
{
    char data;
    struct TreeNode *lchild, *rchild;

};
struct TreeNode* T;
//struct TreeNode R;

void creat_binary_tree(TreeNode* &T);
void pre_order(TreeNode *T);
void mid_order(TreeNode *T);
void post_order(TreeNode *T);

int main()
{
    while (true)
    {
        int select_index = 0;
        cout << "(1)创建一棵新树" << endl;
        cout << "(2)前序遍历" << endl;
        cout << "(3)中序遍历" << endl;
        cout << "(4)后序遍历" << endl;
        cout << "(5)退出系统" << endl;
        cout << "请选择需要的操作:" ;


        cin >> select_index;
        switch(select_index)
        {
        case 1:
            cout << "创建一颗树,其中A->Z字符代表树的数据,用”#“表示空树:" << endl;
            creat_binary_tree(T);
            break;
        case 2:
            cout << "前序遍历:" << endl;
            pre_order(T);
            cout << '\n' << endl;
            break;
        case 3:
            cout << "中序遍历:" << endl;
            mid_order(T);
            cout << '\n' << endl;
            break;
        case 4:
            cout << "后序遍历:" << endl;
            post_order(T);
            cout << '\n' << endl;
            break;
        case 5:
            return 0;
            break;
        default:
            cout << "输入有误,请重新输入:<< endl" ;
        }
    }

    return 0;
}

void creat_binary_tree(TreeNode* &T)
{
    char ch;
    cin >> ch;
    if(ch == '#')
        T = NULL;
    else
    {
        T = new TreeNode;
        T->data = ch;
        creat_binary_tree(T->lchild);
        creat_binary_tree(T->rchild);
    }
}

void pre_order(TreeNode *T)
{
    if(T)
    {
        cout << T->data << " " ;
        pre_order(T->lchild);
        pre_order(T->rchild);
    }
}

void mid_order(TreeNode *T)
{
    if(T)
    {
        mid_order(T->lchild);
        cout << T->data << " " ;
        mid_order(T->rchild);
    }
}

void post_order(TreeNode *T)
{
    if(T)
    {
        post_order(T->lchild);
        post_order(T->rchild);
        cout << T->data << " " ;
    }
}

C++二叉树的建立、前序、中序、后序遍历_第1张图片

你可能感兴趣的:(C语言)