leetCode 104. Maximum Depth of Binary Tree

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

    题目内容:

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

    题目分析:

    一看到这道题,感觉如果用递归的方式解是否就会超时(男人的直觉告诉我!),但是有办法总比没有的好。于是开始码字:

int maxDepth(TreeNode* root) {
    if(root == NULL) return 0;
    else {
        if(maxDepth(root->left) > maxDepth(root->right)
            return maxDepth(root->left) + 1;
        else
            return maxDepth(root->right) + 1;
    }
}
    三下五除二,啪啪啪提交之,结局我早已看到,TLE超时了。正当自己得意早已看穿一切的时候,觉得上面的写法有点点傻,为什么maxDepth(root->left)或者另一边要调用两次呢?没什么必要,可以赋值给变量以供后面用。这也是后来在leetCode上写代码时候的风格,赋值给变量能比重复调用运算符或者函数更节省时间。

int maxDepth(TreeNode* root) {
    if(root == NULL) return 0;
    else {
        int left = maxDepth(root->left);
        int right = maxDepth(root->right);
        return left>right?left+1:right+1;
    }
}
   运行一下,AC了,而且效果貌似还行,跟大多数人一样8ms,花费的时候比较少比较靠前。不过说了,这种递归的肯定不如迭代的运行的省时,于是去讨论区看了一下其他人的解法(发现用递归的时候大家的思路基本没差到哪里去),有同志使用了Java栈和队列分别实现dfs和bfs,而且据称分别是7ms和3ms,下面借用之展示展示,不收广告费,如有侵犯,请联系我,必删之。

public int maxDepth(TreeNode root) {
    if(root == null) {
        return 0;
    }

    Stack<TreeNode> stack = new Stack<>();
    Stack<Integer> value = new Stack<>();
    stack.push(root);
    value.push(1);
    int max = 0;
    while(!stack.isEmpty()) {
        TreeNode node = stack.pop();
        int temp = value.pop();
        max = Math.max(temp, max);
        if(node.left != null) {
            stack.push(node.left);
            value.push(temp+1);
        }
        if(node.right != null) {
            stack.push(node.right);
            value.push(temp+1);
        }
    }
    return max;
}
// 7ms

public int maxDepth(TreeNode root) {
    if(root == null) {
        return 0;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    int count = 0;
    while(!queue.isEmpty()) {
        int size = queue.size();
        while(size-- > 0) {
            TreeNode node = queue.poll();
            if(node.left != null) {
                queue.offer(node.left);
            }
            if(node.right != null) {
                queue.offer(node.right);
            }
        }
        count++;
    }
    return count;
}
// 3ms




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值