【LeetCode热题100(37/100)】二叉树的最大深度
题目地址:链接
思路: 通过递归(先序遍历)的方式获取最大深度
- 到叶子结点时,判断当前深度是否超过最大深度
- 如果不是叶子结点,接着向下遍历
/*** 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 ans = 0;const dfs = (root, deep) => {if(!root) {ans = Math.max(ans, deep);return;}dfs(root.left, deep + 1);dfs(root.right, deep + 1);};dfs(root, 0);return ans;
};