zoukankan      html  css  js  c++  java
  • leetcode-0104 二叉树的最大深度

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

    1.递归

    时间复杂度O(n) 空间复杂度O(h),空间复杂度主要用于递归栈的深度h
    本地使用递归的方式解题非常简单,首先递归终止的条件就是递归到当前节点为null的情况。

    var maxDepth = function(root) {
      if (root === null) {
        return 0
      }
      return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
    };
    

    2.深度优先搜索

    DFS一般都采用栈的形式实现,时间复杂度O(n),空间复杂度O(n),本题让栈的每个位置都存储一个包含两个元素的数组,第一个元素是当前的节点,第二个元素是当前节点对应的深度。这样我们就可以将每个节点的深度都记录下来方便遍历到下一个元素的时候使用。由于本题没有遍历顺序性方面的要求,只要求每个节点都遍历到,因此DFS和BFS两种方案都是可以的。

    var maxDepth = function(root) {
        const stack = [];
        if (root === null) return 0;
        stack.push([root, 1]);
        let depth = 0;
        while (stack.length > 0) {
            const [node, curDepth] = stack.pop();
            depth = Math.max(depth, curDepth);
            node.left && stack.push([node.left, curDepth + 1]);
            node.right && stack.push([node.right, curDepth + 1]);
        }
        return depth;
    };
    

    3.广度优先搜索

    BFS一般都采用队列的形式实现,时间复杂度O(n),空间复杂度O(n)

    var maxDepth = function(root) {
        const queue = [];
        if (root == null) return 0;
        let depth = 0;
        queue.push([root, 1]);
        while (queue.length > 0) {
            const [node, curDepth] = queue.shift();
            depth = Math.max(depth, curDepth);
            node.left && queue.push([node.left, curDepth + 1]);
            node.right && queue.push([node.right, curDepth + 1]);
        }
        return depth;
    };
    

    更多LeetCode题解和数据结构方面的内容,可以关注我的github,求个star~ ▄█▔▉●

  • 相关阅读:
    012 字典
    011 递归
    010 函数与闭包
    009 格式化
    000 机器学习的概念原理
    008 元组
    007 列表
    005 Numpy的基本操作
    071 SparkStreaming与SparkSQL集成
    070 DStream中的transform和foreachRDD函数
  • 原文地址:https://www.cnblogs.com/guolizhi/p/12769038.html
Copyright © 2011-2022 走看看