二叉树的遍历

来源:互联网 发布:软件学报审稿流程 编辑:程序博客网 时间:2024/04/25 04:28

二叉树的后序遍历:

题目描述

给定一颗二叉树,要求输出二叉树的深度以及后序遍历二叉树得到的序列。本题假设二叉树的结点数不超过1000

输入

输 入数据分为多组,第一行是测试数据的组数n,下面的n行分别代表一棵二叉树。每棵二叉树的结点均为正整数,数据为0代表当前结点为空,数据为-1代表二叉 树数据输入结束,-1不作处理。二叉树的构造按照层次顺序(即第1层1个整数,第2层2个,第3层4个,第4层有8个......,如果某个结点不存在以 0代替)。

输出

输出每棵二叉树的深度以及后序遍历二叉树得到的序列。

样例输入
21 -11 2 0 3 4 -1
样例输出

1 1

3 3 4 2 1


代码:

#include <cmath>#include <cstdio>#include <algorithm>#include <iostream>#include <malloc.h>#define N 1005 using namespace std;typedef struct biNode{int data;biNode* lchild;biNode* rchild;}node,*biTree;//node* 等价于biTree biTree* q[N];//注意这里不是biTree q[N],q数组保存的是指向结点的结点的地址(指针的指针的地址)biTree root;void createTree()//创建二叉树{int num;int i=0,j=0;//i,j保存的下标 bool flag=true;while(scanf("%d",&num)==1&&num!=-1){biTree p=(biTree)malloc(sizeof(node));if(flag)//创建根结点,用flag变量控制 {if(num==0)//当输入为 0 -1时,直接退出 exit(0); root=p;root->data=num;root->lchild=NULL;root->rchild=NULL;q[i++]=&root->lchild;//注意这代码是怎么写的 q[i++]=&root->rchild;flag=false;}else{if(num!=0){p->data=num;p->lchild=NULL;p->rchild=NULL;q[i++]=&p->lchild;q[i++]=&p->rchild;*q[j++]=p;}else{delete p;j++;//也要j加1 }}}}int deepth(biTree t)//递归,求二叉树的深度 {if(t==NULL)return 0;int x=deepth(t->lchild);int y=deepth(t->rchild);return max(x,y)+1;}void traverse(biTree t)//递归,后序遍历 {if(t==NULL)return ;traverse(t->lchild);traverse(t->rchild);cout<<  t->data  <<" ";}int main(){int T;scanf("%d",&T);while(T--) {createTree(); cout<<deepth(root)<<" ";traverse(root);}return 0;} 


0 0
原创粉丝点击