二叉树的深度

参考  https://blog.csdn.net/hyqsong/article/details/50807183

 

1.非递归 

采用层次遍历的方法,类似bfs的解法

  • 每遍历一层,level++;
  • 每一层,需使用一个变量len记录该层的结点个数,也就是队列的当前长度,然后依次在队列中访问该层的len个结点(将队列中len个元素出队列),并将下一层左右节点入队列。
     1 int TreeDepth(TreeNode* pRoot)
     2     {
     3      queue<TreeNode*> q;
     4         if(!pRoot) return 0;
     5         q.push(pRoot);
     6         int level=0;
     7         while(!q.empty()){
     8             int len=q.size();
     9             level++;
    10             while(len--){
    11                 TreeNode* tem=q.front();
    12                 q.pop();
    13                 if(tem->left) q.push(tem->left);
    14                 if(tem->right) q.push(tem->right);
    15             }
    16         }
    17         return level;
    18     } 
    19  

     

递归

 

1  int TreeDepth(TreeNode* pRoot)
2     {
3         if (pRoot == NULL)
4             return 0;
5         else
6             return max(1 + TreeDepth(pRoot->left), 1 + TreeDepth(pRoot->right));
7 
8     }
9  

 

posted on 2019-03-04 09:42  wait_for_you  阅读(120)  评论(0编辑  收藏  举报

导航