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

    待补充

  • 相关阅读:
    单例模式
    java笔记 chapter7 抽象类和数组
    java笔记 chapter6 StringBuffer类和String Bulider类,Math类 Date类,Calendar类
    设计上的若干问题
    Java中的二次分发
    关于抽象
    SSI框架下同一个Bean加载了2次问题解决
    Hello 2015
    关于window.location.href is not a function在FF,chrom报错问题
    使用Eclipse的一些小心得!
  • 原文地址:https://www.cnblogs.com/manru75/p/13056757.html
Copyright © 2011-2022 走看看