递归按层遍历二叉树算法

递归模拟队列按层遍历二叉树,简单,易懂,先序创建二叉树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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值