码迷,mamicode.com
首页 > 其他好文 > 详细

求二叉树的高度(非递归)

时间:2019-06-29 22:03:44      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:++   高度   非递归   return   c++实现   color   二叉树的高度   ret   level   

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

 

求二叉树的高度(非递归)

标签:++   高度   非递归   return   c++实现   color   二叉树的高度   ret   level   

原文地址:https://www.cnblogs.com/daoko/p/11107877.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!