Topic describes

Given a binary tree, find its maximum depth.

The depth of a binary tree is the number of nodes along the longest path from the root node to the farthest leaf node.

Note: Leaf nodes are nodes that have no child nodes. Example: given a binary tree [3,9,20,null,null,15,7],

Returns its maximum depth of 3.

//
// 1, create a variable to record the maximum depth
// 2, depth-first traverses the entire tree and records the level of each node, while constantly refreshing the maximum depth variable
// 3, return the maximum depth variable at the end of the walk
// 4, please follow my wechat official account for more content: Hand touch hand advance

/** * 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) {
  let res = 0
  const dfs = (n,level) = > {
    if(! n)return
    if(! n.left && ! n.right) {// Check whether it is a leaf node
      res = Math.max(res, level)
    }
    dfs(n.left, level + 1)
    dfs(n.right, level + 1)
  }
  dfs(root, 1) // level starts with 1
  return res
};

// The title is reprinted from licou official website:
// https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
Copy the code