非递归遍历求二叉排序树的深度
生活随笔
收集整理的這篇文章主要介紹了
非递归遍历求二叉排序树的深度
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、代碼?
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <queue> #define Maxsize 100 using namespace std; typedef struct BTNode{int data;struct BTNode *lchild,*rchild; }BTNode;//利用非遞歸中序遍歷求二叉排序樹的深度 int BSTDeepth(BTNode *bt) {BTNode *p;int deepth=0; //二叉樹的深度 if(bt!=NULL){int h=0; //高度 int top=-1;BTNode *stack[Maxsize];p=bt;while(p!=NULL||top!=-1){while(p!=NULL){stack[++top]=p;p=p->lchild;h++; //深度加1 }if(top!=-1) //棧不為空 {p=stack[top--]; //出棧if(p==bt) //若出棧為根節點,則將高度置為1 h=1;if(p->rchild==NULL) //為葉子結點,記錄其高度 { // cout<<"數據為:"<<p->data<<"高度為:"<<h<<endl;if(h>deepth) //若當前的記錄的高度大于已經記錄的深度,則替換 deepth=h; // cout<<"deepth:"<<deepth<<endl;h--; }p=p->rchild;}}}return deepth; }//二叉排序樹的插入算法 int BSTInsert(BTNode *&bt,int key) {if(bt==NULL){bt=(BTNode*)malloc(sizeof(BTNode));bt->lchild=bt->rchild=NULL;bt->data=key;return 1;}else if(key==bt->data)return 0; //插入失敗else if(key<bt->data)return BSTInsert(bt->lchild,key); //插入左子樹中 elsereturn BSTInsert(bt->rchild,key); //插入右子樹中 }//二叉排序樹的創建 void CreateBST(BTNode *&bt,int key[],int n) {int i;bt=NULL;for(i=0;i<n;i++)BSTInsert(bt,key[i]); }//二叉樹的層次遍歷 void LevelOrderTraverse(BTNode *bt)//層次遍歷 {queue<BTNode*> Queue;if(!bt){cout<<"空樹!"<<endl;;return;}Queue.push(bt);while(!Queue.empty()){bt=Queue.front();Queue.pop();cout<<bt->data<<" ";if(bt->lchild)Queue.push(bt->lchild);if(bt->rchild)Queue.push(bt->rchild); }cout<<endl; } int main() {BTNode *bt; int n; // int key[10]={45,24,55,12,37,53,60,28,40,70}; // int key[10]={1,2,3,4,5,6,7,8,9,10}; int key[Maxsize];cout<<"元素個數:";cin>>n;for(int i=0;i<n;i++)cin>>key[i];CreateBST(bt,key,n);cout<<"創建完畢!層次遍歷結果如下:"<<endl; LevelOrderTraverse(bt);cout<<"深度為:"<<BSTDeepth(bt)<<endl;return 0; }二、運行結果
不同的輸入順序會生成不同的二叉排序樹,深度也不同!
?
總結
以上是生活随笔為你收集整理的非递归遍历求二叉排序树的深度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设CPU中各部件及其相互连接关系如下图所
- 下一篇: 邻接矩阵和邻接表的相互转化