zoukankan      html  css  js  c++  java
  • 力扣----5. 二叉树的最大深度(JavaScript, Java实现)

    题目描述:

    给定一个二叉树,找出其最大深度。

    二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

    说明: 叶子节点是指没有子节点的节点。

    示例:
    给定二叉树 [3,9,20,null,null,15,7],

    3
    /
    9 20
    /
    15 7
    返回它的最大深度 3 。

    JavaScript实现:

    DFS:  深度优先搜索,递归

    思想:某个节点的高度为Max(左子树高度,右子树高度) + 1

    时间复杂度:O(n)

    空间复杂度:O(logn ~ n)

    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number}
     */
    var maxDepth = function(root) {
        let height = 0;
        if(!root){
            return 0;
        }else {
            let left = maxDepth(root.left);
            let right = maxDepth(root.right);
            height = Math.max(left, right) + 1;
        }
        return height
    };

    BFS:  广度优先搜索

    思想:一层一层的遍历,需要用到队列,每遍历完一层自己出队列,孩子进队列,直到队列里面没有东西

    时间复杂度:O(n)

    空间复杂度:O(n)

    var maxDepth = function(root) {
        if(!root) return 0;
        let queue = [root];
        let depth = 0;
        while(queue.length){
            let queueLength = queue.length;
            while(queueLength){
                let first = queue.shift();
                first.left && queue.push(first.left)
                first.right && queue.push(first.right)
                queueLength--;
            }
            depth++
        }
        return depth;
    };

    JAVA实现:

    待补充

  • 相关阅读:
    Cache,ViewState,Session,Application,Static变量
    Java -- 通过 URLConnection 进行http请求中文乱码
    maven
    SpringMVC restful风格下载文件,文件后缀被截掉
    vim 命令
    CentOS -- 命令
    json -- fastjson如何序列化@Transient的字段
    SpringBoot -- 配置mysql、hibernate
    Java -- 泛型父类中获取子类的泛型T
    Excel
  • 原文地址:https://www.cnblogs.com/manru75/p/13056757.html
Copyright © 2011-2022 走看看