剑指offer_55_二叉树的深度I【javascript】

51 阅读1分钟

题目链接

leetcode.cn/problems/er…

题目 二叉树的深度【简单】

输入一棵二叉树的根节点,求该树的深度。从根节点到叶及诶单依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

示例

输入:root = [1, 2, 2, 3, null, null, 5, 4, null, null, 4]
输出: 4
解释: 上面示例中的二叉树的最大深度是 4,沿着路径 1 -> 2 -> 3 -> 41 -> 2 -> 5 -> 4 到达叶节点的最长路径上有 4 个节点。

提示:

题解

深度优先

  • 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。
  • 空间复杂度 O(N) : 最差情况下(当树退化为链表时),递归深度可达到 N 。
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var calculateDepth = function(root) {
    if(root == null) return 0;
    return Math.max(calculateDepth(root.left), calculateDepth(root.right)) + 1;
};

广度优先(层序遍历)

  • 时间复杂度 O(N) : N 为树的节点数量,计算树的深度需要遍历所有节点。
  • 空间复杂度 O(N) : 最差情况下(当树平衡时),队列 queue 同时存储 N/2 个节点。
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var calculateDepth = function(root) {
    if(root == null) return 0;
    let queue = [root], temp = [];
    let depth = 1;
    while(queue.length) {
        const node = queue.shift();
        if (node.left) temp.push(node.left);
        if(node.right) temp.push(node.right);

        if(queue.length === 0 && temp.length){
            depth++;
            queue.push(...temp)
            temp = [];
        } 
    }
    return depth;
};