二叉树简易操作(递归遍历)

来源:互联网 发布:java websocket api 编辑:程序博客网 时间:2024/05/22 04:27
//------------------------------------------------------------------------------// 二叉树//------------------------------------------------------------------------------#include <iostream>using namespace std;typedef struct tree{intdata;// 节点值tree*parent;// 父节点tree*   leftTree;// 左孩子tree*rightTree;// 右孩子} Tree, *LPTree;//******************************************************************************// Name: CreateTree// Desc: 创建一颗根为root的树//******************************************************************************Tree* CreateTree(int root){Tree* myTree= new Tree;myTree->data= root;myTree->parent= NULL;myTree->leftTree= NULL;myTree->rightTree= NULL;return myTree;}//******************************************************************************// Name: InitATree// Desc: 初始化一颗树,即从根部开始插入一些树(满二叉树填充法)//******************************************************************************Tree* InitATree(Tree* &tre, int data){if(tre == NULL){return NULL;}// 产生一颗空树Tree* newTree= new Tree;newTree->data= data;newTree->parent= NULL;newTree->leftTree= NULL;newTree->rightTree= NULL;// 保存要插入节点的父亲节点,因为当找到要插入的位置的时候,它就是一个NULL指针Tree* currentParent = NULL;// 先找到插入节点Tree* tempTree = tre;while(tempTree != NULL){// 保存当前的父亲节点,用以插入新节点的时候,保存父子连接关系currentParent = tempTree;if(data < tempTree->data){tempTree = tempTree->leftTree;}else{tempTree = tempTree->rightTree;}}// 下面的代码是必须的,犯错误代码如:没有下面的if...else...语句,// 直接tempTree=newTree;这是不允许的,改变的只是一个单独的指针罢了// (单链表,双链表,队列都要注意这种问题)if(data < currentParent->data){currentParent->leftTree = newTree;}else{currentParent->rightTree = newTree;}newTree->parent=currentParent;return tre;}//******************************************************************************// Name: FirstPrint// Desc: 先根遍历二叉树//******************************************************************************void FirstPrint(Tree* tre){if(tre != NULL){cout<<tre->data<<" ";FirstPrint(tre->leftTree);FirstPrint(tre->rightTree);}}//******************************************************************************// Name: CenterPrint// Desc: 中根遍历//******************************************************************************void CenterPrint(Tree* tre){if(tre != NULL){CenterPrint(tre->leftTree);cout<<tre->data<<" ";CenterPrint(tre->rightTree);}}//******************************************************************************// Name: CenterPrint// Desc: 后根遍历//******************************************************************************void AfterPrint(Tree* tre){if(tre != NULL){AfterPrint(tre->leftTree);AfterPrint(tre->rightTree);cout<<tre->data<<" ";}}int main(){int root;cin>>root;Tree* myTree = CreateTree(root);cout<<"成功创建根为"<<root<<"的树"<<endl;int childData;while(cin>>childData){myTree = InitATree(myTree, childData);}// 先根遍历cout<<"先根遍历:"<<endl;FirstPrint(myTree);cout<<endl;// 中根遍历cout<<"中根遍历:"<<endl;CenterPrint(myTree);cout<<endl;// 后根遍历cout<<"后根遍历:"<<endl;AfterPrint(myTree);cout<<endl;system("pause");return 0;};

原创粉丝点击