二叉树的一些简单算法(一)

来源:互联网 发布:国家卫生网络统计报表 编辑:程序博客网 时间:2024/05/16 10:29

                                                                                 二叉树的一些简单算法(一)

      由于最近数据结构学到了树的这一章节,而二叉树的算法一直被各大公司视为必考内容,因此,身为小菜菜的我也决定写几篇关于二叉树的算法;

       这次我简单的写一下二叉树的创建和遍历算法;

 

#include <iostream>using namespace std;typedef char T;class BTree{public:BTree * left; BTree * right;T data;};class BiTree{public:BTree * CreateTree(){//二叉树的创建char ch;BTree * root;cin >> ch;if (ch != '#'){root = new BTree;root->data = ch; root->left = CreateTree();root->right = CreateTree();}else{root = NULL;}return root;}void PreSort(BTree * root){//前序输出if(root){cout << root->data;PreSort(root->left);PreSort(root->right);}}void MidSort(BTree * root){//中序输出if(root){PreSort(root->left);cout << root->data;PreSort(root->right);}}void FloSort(BTree * root){//后序输出if(root){PreSort(root->left);PreSort(root->right);cout << root->data;}}};int main(){BiTree tree;BTree * root;root = tree.CreateTree();tree.PreSort(root);cout << endl;tree.MidSort(root);cout << endl;tree.FloSort(root);return 0;}

  

 

 

0 0