104. Maximum Depth of Binary Tree

Description

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Solution

Solution 1

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * Traverse the binary tree with Breadth-First Search (BFS) algorithm
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    "use strict";
    let result = 0;
    let queue = root ? [root] : [];
    while(queue.length) {
        let len = queue.length;
        for (let i = 0; i < len; i++) {
            if (queue[i].left) {
                queue.push(queue[i].left);
            }
            if (queue[i].right) {
                queue.push(queue[i].right);
            }
        }
        result++;
        queue = queue.slice(len);
    }
    return result;
};

Solution 2

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * Traverse the binary tree with Depth-First Search (DFS) algorithm (preorder)
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    "use strict";
    function dfs(node, depth) {
        if (!node) {
            return depth-1;
        }
        return Math.max(dfs(node.left, depth+1), dfs(node.right, depth+1));
    }
    return dfs(root, 1);
};

results matching ""

    No results matching ""