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实现:

    待补充

  • 相关阅读:
    JS命名空间的使用
    PHPexcel的用法
    python爬取百度贴吧帖子
    python自动抢票
    int 与 String 与 char 之间的互相转换
    数据库备份和恢复
    Mysql 基础
    Mysql错误:Every derived table must have its own alias
    frameset框架集
    文件的上传(TCP)
  • 原文地址:https://www.cnblogs.com/manru75/p/13056757.html
Copyright © 2011-2022 走看看