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

待补充

posted @ 2020-06-06 22:17  灭世的蜜糖  阅读(796)  评论(0编辑  收藏  举报