求二叉樹的高度(非遞歸)


非遞歸就是在層次遍歷的基礎上加上個depth,len變量來記錄即可,有點類似於BFS

用c++實現如下:


 

 

 1 int TreeDepth(TreeNode* pRoot)
 2     {
 3      queue<TreeNode*> q;
 4         if(!pRoot) return 0;
 5         q.push(pRoot);
 6         int depth=0;
 7         while(!q.empty()){
 8             int len=q.size();//隊列的當前大小
 9             depth++;
10             while(len--){ //循環完就是一層都退出隊列了
11                 TreeNode* temp=q.front();//表頭
12                 q.pop();
13                 if(temp->left) q.push(temp->left);
14                 if(temp->right) q.push(temp->right);
15             }
16         }
17         return level;
18     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM