非递归就是在层次遍历的基础上加上个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 }