層次遍歷求二叉樹的高度(非遞迴)
阿新 • • 發佈:2019-01-30
來自大佬群主的第二題
所謂層次遍歷,是將二叉樹中的元素從根節點按照節點層數一層層的輸出。
程式碼如下:
int GetDepth(bitreenode *root) { int depth=0; bitreenode *p=root; queue<bitreenode*> q; q.push(p); //根指標入隊 while(!q.empty()) { depth++; //高度加一 int width=q.size(); //獲取當前層次寬度 for(int i=0;i<width;i++) { p=q.front(); //獲取隊頂元素 q.pop(); //彈出隊頂元素 if(p->leftchild!=NULL) //左孩子入隊 q.push(p->leftchild); if(p->rightchild!=NULL) //右孩子入隊 q.push(p->rightchild); } } cout<<depth<<endl; }