非遞歸就是在層次遍歷的基礎上加上個depth,len變量來記錄便可,有點相似於BFSc++
用c++實現以下:spa
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 }