C++求二叉树深度的两种方法

今天在leetcode中碰到了求二叉树的深度问题,于是总结一下这两种方法

  1. 方法一是用递归的方法,方法二是借助队列和层序遍历的思想
#include<iostream>
#include<queue>
using namespace std;
//构建二叉树
struct TreeNode
{
    int val;
   struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x):val(x),left(NULL),right(NULL){}
};


//方法一:判断树不为空就一直遍历下去
class Solution {
public:
    int TreeDepth(TreeNode* pRoot){
        if(!pRoot) return 0 ;
            return max(1+TreeDepth(pRoot->left), 1+TreeDepth(pRoot->right));
    }
};
//方法二:利用层序遍历的思想,每一层都弹出队列,深度才加一
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {    if(pRoot==NULL)return 0;
         int depth=0;
        TreeNode* p1=pRoot;
        TreeNode* front;
        queue<TreeNode*> q1;
        q1.push(p1);
        while(!q1.empty())
        {  
         depth++;
         int size1=q1.size();
         int count=0;
       //每次弹出所有的队列元素,然后让深度加一//
         while(count<size1)
             {
                 front=q1.front();
                 q1.pop();
                 count++;
                if(front->left!=NULL)
                    {
                    q1.push(front->left);
                    }
                if(front->right!=NULL)
                    {
                    q1.push(front->right);
                    }
             }
            
        }
     return depth;
    }
};



  • 4
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值