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

    待补充

  • 相关阅读:
    HDU 6071
    HDU 6073
    HDU 2124 Repair the Wall(贪心)
    HDU 2037 今年暑假不AC(贪心)
    HDU 1257 最少拦截系统(贪心)
    HDU 1789 Doing Homework again(贪心)
    HDU 1009 FatMouse' Trade(贪心)
    HDU 2216 Game III(BFS)
    HDU 1509 Windows Message Queue(队列)
    HDU 1081 To The Max(动态规划)
  • 原文地址:https://www.cnblogs.com/manru75/p/13056757.html
Copyright © 2011-2022 走看看