码迷,mamicode.com
首页 > 其他好文 > 详细

按层输出二叉树

时间:2015-05-10 15:42:13      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:二叉树   遍历   

#include <iostream>  
#include<queue>  
using namespace std;  
struct treeNode
{
int value;
treeNode* left;
treeNode* right;
}; 
int getHeight(treeNode * root)
 {
     if(root==NULL)
	     return 0;    
  else 
   return (getHeight(root->left)>getHeight(root->right)?getHeight(root->left):getHeight(root->right))+1;
} 
void  ByLevel(treeNode * root,int level)
{
  if(root==NULL||level<0)
       return ;
   if (level==0)
       cout<<root->value<<" ";
   else 
    {
       ByLevel(root->left,level-1);
	   ByLevel(root->right,level-1);
	
    }    
	

}


treeNode * treeInsert(treeNode* head,int n)  
{    
    treeNode* newNode=new treeNode;  
    newNode->left=newNode->right=NULL; 
    newNode->value=n;  
    if (head==NULL)  
    {    
          
          return newNode;  
    }  
    treeNode *head1=head,*head2=NULL;  
        while (head1!=NULL)//先确定待插入的父亲节点   
             {     
               head2=head1;  
                if(head1->value>n)  
                    head1=head1->left;  
                else  
                   head1=head1->right;  
                  
             }   
             if(head2->value>n)  
                {  
                    head2->left=newNode;  
                      
                }  
                  
                else   
                {  
                     head2->right=newNode;  
                }  
                   
          return head;    
} 
      
int main()
{  
  treeNode *head=NULL;
	head=treeInsert(head,5);
	head=treeInsert(head,1);
	head=treeInsert(head,9);
	head=treeInsert(head,3);
	head=treeInsert(head,8);
	head=treeInsert(head,6);
	  int high=getHeight(head);
	  for(int i=0;i<high;i++)
	    {
	      cout<<"LEVEL:"<<i+1<<endl; 
		  ByLevel(head,i);
		  cout<<endl;
	      cout<<"__________________"<<endl; 
	    } 
	  return 0; 
}

按层输出二叉树

标签:二叉树   遍历   

原文地址:http://blog.csdn.net/hero_zouzongling/article/details/45621315

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!