Topic describes

Leetcode link: leetcode-cn.com/problems/er…

Enter the root node of a binary tree to find the depth of the tree. The nodes (including root and leaf nodes) that pass from the root node to the leaf node form a path of the tree. The longest length of the path is the depth of the tree.

Such as:

Given a binary tree [3,9,20,null,null,15,7],


    3
   / \
  9  20
    /  \
   15   7
Copy the code

Returns its maximum depth of 3.

Tip:

  • The number of nodes is less than = 10000

Thinking to describe

The method of recursion is used to find the depth of the left and right subtrees recursively, and the maximum depth of the left and right subtrees is added by one.

AC code

/** * 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) {
    if(root === null) {
        return 0;
    }
    return Math.max(maxDepth(root.left), maxDepth(root.right))+ 1
};
Copy the code

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign