Binary Tree Traversals ,create binary tree as follow (Figure-1) in computer

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Binary Tree Traversals ,create binary tree as follow (Figure-1) in computer相关的知识,希望对你有一定的参考价值。

write out the functions of inorder , preorder , postorder and levelorder, and output the their results. And compute the leaf number and height of the binary tree.
Hint: You may choose suitable representation, such as linked representation is often used.
不是翻译题,回答请C黏贴代码

参考技术A 如有不合题意之处,谅解,可以自己再改改。。
#include<iostream>
using namespace std;
#include<stdlib.h>
#include<stdio.h>
#define OK 1
#define ERROR 0
#define OVERFLOE -2
typedef char ElemType;
const int maxlength=30;//结点个数不超过30个
typedef struct BiTreeNode

ElemType data;
struct BiTreeNode*leftchild,*rightchild;
BiTreeNode,*BiTree;
void createBiTree(BiTree&t)

ElemType ch;
cin>>ch;
if(ch=='#')t=NULL;
else

if(!(t=new BiTreeNode))
exit(OVERFLOE);
t->data=ch;//生成根节点
createBiTree(t->leftchild);//构造左子树
createBiTree(t->rightchild);//构造右子树

//createBiTree
void Inorder(BiTree&t)//递归函数:中序次序遍历以t为跟的子树

if(t!=NULL)

Inorder(t->leftchild);
cout<<t->data<<"";
Inorder(t->rightchild);


void Postorder(BiTree&t)

if(t!=NULL)

Postorder(t->rightchild);

Postorder(t->leftchild);
cout<<t->data<<"";


void levelorder(BiTree t)//层次遍历

BiTree Q[maxlength];
int front=0,rear=0;
BiTree p;
if(t)//根结点入列

Q[rear]=t;
rear=(rear+1)%maxlength;

while(front!=rear)

p=Q[front];//对头元素出队
front=(front+1)%maxlength;
cout<<p->data<<"";
if(p->leftchild)//左孩子不为空,入队

Q[rear]=p->leftchild;
rear=(rear+1)%maxlength;

if(p->rightchild)//右孩子不为空,入队

Q[rear]=p->rightchild;
rear=(rear+1)%maxlength;



int depth(BiTree t)

int depthval,depthleft,depthright;
if(!t)

depthval=0;

else

depthleft=depth(t->leftchild);
depthright=depth(t->rightchild);
depthval=1+(depthleft>depthright?depthleft:depthright);

return depthval;

int countleaf(BiTree t)

int m,n;
if(!t)

return 0;

if(!t->leftchild&&!t->rightchild)

return 1;

else

m=countleaf(t->leftchild);
n=countleaf(t->rightchild);
return (m+n);



#include"BiTree.h"
void main()

cout<<"请输入二叉树序列,如:AB##C##D"<<endl;
BiTree tree;
createBiTree(tree);
cout<<"二叉树创建完成!"<<endl;
cout<<"中序遍历该二叉树输出结果:";
Inorder(tree);
cout<<endl;
cout<<"后序遍历该二叉树输出结果:";
Postorder(tree);
cout<<endl;
cout<<"二叉树深度为:";
cout<<depth(tree)<<endl;
cout<<"二叉树的总叶子个数为:";
cout<<countleaf(tree)<<endl;
cout<<"以队列为辅助存储结构实现二叉树的层次遍历为:";
levelorder(tree);
本回答被提问者和网友采纳

以上是关于Binary Tree Traversals ,create binary tree as follow (Figure-1) in computer的主要内容,如果未能解决你的问题,请参考以下文章

HDU 1710 Binary Tree Traversals(二叉树)

HDU 1710 Binary Tree Traversals(二叉树)

二叉树hdu 1710 Binary Tree Traversals

hdu 1710 Binary Tree Traversals 前序遍历和中序推后序

HDU 1710Binary Tree Traversals(已知前序中序,求后序的二叉树遍历)

[PAT] A1086 Tree Traversals Again