递归按层遍历二叉树算法

来源:互联网 发布:lol挂机辅助软件 编辑:程序博客网 时间:2024/05/21 20:32

递归模拟队列按层遍历二叉树,简单,易懂,先序创建二叉树Create_tree(),递归求树深度depth,一层层递归打印节点!

 

/*  * author : qiu  * coding : utf-8  * time : 2014-12--  * fun:递归按层遍历二叉树  **/#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <iostream>#include <algorithm>#include <string>#include <vector>#include <malloc.h>#define debug puts("-----")#define pi (acos(-1.0))#define eps (1e-8)#define inf (1<<28)using namespace std;typedef struct bnode{          int data;          struct bnode *lchild;          struct bnode *rchild;          }bnode, *btree;// 先序创建二叉树void Create_tree(btree &root){   int num;   scanf("%d", &num);   if(num != -1){    root=(btree)malloc(sizeof(bnode));    root->data=num;  Create_tree(root->lchild);  Create_tree(root->rchild);  }  else {       root = NULL;  }}//  递归节点void Printree_level(btree root, int level){       if(!root || level < 1){           return ;       }       if(level == 1)       printf("%d ", root->data);      Printree_level(root->lchild, level-1);      Printree_level(root->rchild, level-1);}// 树深度int Depth_tree(btree root){ int lcount, rcount; if(!root)     return 0; else{      lcount = Depth_tree(root->lchild);      rcount = Depth_tree(root->rchild);        if(lcount < rcount)         return rcount + 1;         else         return lcount + 1; }}//  按层遍历打印void Printree_traverse(btree root){if(!root)return ;   int depth = Depth_tree(root);  for(int i=1; i<=depth; i++){             Printree_level(root, i);  }  printf("\n");}int main(){    btree Root;       Create_tree(Root);       Printree_traverse(Root);return 0;}


0 0
原创粉丝点击