104. Maximum Depth of Binary Tree

Leetcode link

题目简介

/**
 * @param {TreeNode} root
 * @return {number}
 */

题目给我们一个二叉树根节点 root,要求我们计算树的深度

解题思路

我们直接深度遍历当前的树,在每个节点返回的时候把深度 + 1 即可

Javascript

/**
 * 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 maxDepth = function(root) {
    if(!root) {
        return 0
    }

    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
};

results matching ""

    No results matching ""