leetcode 104二叉树的深度

题目:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

思路一:广度优先遍历
分析:求出树的最大深度,也就是计算树有多少层,访问每层元素,然后将层数+1,直到最后一层,即可的最大深度。

int maxDepth(TreeNode* root) {
       
       int res=0;
       if(root==NULL)
        return res;
        queue<TreeNode*>que;
        que.push(root);
        while(!que.empty())
        {


            int len=que.size();
            for(int i=0;i<len;i++)
            {
                TreeNode*node=que.front();
                que.pop();
                if(node->left)
                 que.push(node->left);
                if(node->right)
                  que.push(node->right);
            }
            res++;
        }
        return res;


        
    }

思路二; 深度优先遍历(后序遍历)

分析:后序遍历
步骤:

  1. 确定递归函数的参数和返回值

              确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。
    
  2. 确定递归终止的条件

        如果为空节点的话,就返回0,表示高度为0
    
  3. 确定单层逻辑

       先求左子树的深度,再求右子树的深度,最后取左右子树深度最大的+1就是当前结点的树的深度作为返回值
    
class Solution {
public:
    int getDepth(TreeNode* node) {
        if (node == NULL) return 0;
        int leftDepth = getDepth(node->left);       // 左
        int rightDepth = getDepth(node->right);     // 右
        int depth = 1 + max(leftDepth, rightDepth); // 中
        return depth;
    }
    int maxDepth(TreeNode* root) {
        return getDepth(root);
    }
};

精简后的代码
 
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
};
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值