#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