二叉树的基本操作

来源:互联网 发布:袁和平 知乎 编辑:程序博客网 时间:2024/06/08 00:12

建立一颗二叉树(不要用数组),求二叉树的前序遍历序列,中序遍历序列,后序遍历序列,层序遍历序列,输出叶子,叶子数,和数的高度(根节点为第1层)

例如下图:


输入样例:

A B D # # # C E G # # H # # F # #

输出样例:

preorder: A B D C E G H F
inorder: D B A G E H C F
postorder: D B G E H C F A
levelorder: A B C D E F G H
D G H F leaves: 4
height: 4

#include <iostream> #include <algorithm>#include <queue> using namespace std;typedef struct treenode* tptr;queue<tptr> q;struct treenode{char data;tptr left,right;}*root;tptr creat(tptr t)//建树{t=new treenode;char ch;cin>>ch;if(ch=='#')t=NULL;else{t->data=ch;t->left=creat(t->left);t->right=creat(t->right);}return t;}void preorder(tptr t)//前序遍历{if(t){cout<<t->data<<" ";preorder(t->left);preorder(t->right);}}void inorder(tptr t)//中序遍历{if(t){inorder(t->left);cout<<t->data<<" ";inorder(t->right);}} void postorder(tptr t)//后序遍历{if(t){inorder(t->left);inorder(t->right);cout<<t->data<<" ";}}void levelorder(tptr t)//层序遍历{tptr tmp;if(t){q.push(t);while(!q.empty()){tmp=q.front();cout<<tmp->data<<" ";    q.pop();    if(tmp->left)q.push(tmp->left);    if(tmp->right)q.push(tmp->right);}}}int countleaves(tptr t)//数叶子{if(!t)return 0;if(!t->left&&!t->right){cout<<t->data<<" ";return 1;}return countleaves(t->left)+countleaves(t->right);}int height(tptr t)//求树的高度{if(t)return max(height(t->left),height(t->right))+1;return 0;}int main() {root=creat(root);cout<<"preorder: "; preorder(root);cout<<endl;cout<<"inorder: "; inorder(root);cout<<endl;cout<<"postorder: "; postorder(root);cout<<endl;cout<<"levelorder: "; levelorder(root);cout<<endl;cout<<"leaves: "<<countleaves(root)<<endl;cout<<"height: "<<height(root)<<endl;return 0;  }  



0 0
原创粉丝点击