【简单】Leetcode-二叉树的最大深度//递归使用//队列使用

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]

        3
       / \
      9   20
         /  \
        15   7
返回最大深度3

1.递归法
这里转载一下本题题解区里的解答,原地址如下:
漫画:绝对能看懂的DFS题解
在这里插入图片描述

int maxDepth(TreeNode* root) {
        if(root == NULL){
            return 0;
        }
        else{
            int depthl = maxDepth(root -> left);
            int depthr = maxDepth(root -> right);
            if(depthl > depthr)
                return depthl + 1;
            else
                return depthr + 1;
        }
    }

2.利用队列 法1
思路:这是我想到的办法。用size记录每一层的结点数,然后用for循环,从0到size递增将下一层入队列,再用size记录这一层的结点数,以此循环。其中用depth来记录层数

int maxDepth(TreeNode* root) {
        if(!root) return 0;
        queue<TreeNode*> q;
        TreeNode* p;
        q.push(root);
        int depth = 0, size = 0;
        while(!q.empty())
        {
            ++depth;
            size = q.size();
            for(int i = 0; i < size; i++)
            {
                p = q.front();
                if(p -> left != NULL) q.push(p -> left);
                if(p -> right != NULL) q.push(p -> right);
                q.pop();
            }
        }
        return depth;
    }

3.利用队列 法2
这个方法效率更高一点。用flag标记这一层所有元素中的最后一个,当当前p指向的元素和flag是同一个时,说明这一层结束了,depth+1.

int maxDepth(TreeNode* root) {
        if(!root) return 0;
        queue<TreeNode*> q;
        TreeNode* p;
        q.push(root);
        int depth = 0;
        TreeNode* flag = root;
        while(!q.empty())
        {
            p = q.front();
            q.pop();
            if(p -> left != NULL) q.push(p -> left);
            if(p -> right != NULL) q.push(p -> right);
            if(flag == p) 
            {
                ++depth;
                flag = q.back();
            }
        }
        return depth;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值