Voyz's Studio.

LeetCode算法笔记--二叉树的最大深度

字数统计: 144阅读时长: 1 min
2020/12/27 Share

LeetCode算法笔记-Day52

104. Maximum Depth of Binary Tree

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.

example:

1
2
3
4
5
6
7
8
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7

return its depth = 3.

Analyse:

DFS

深度优先遍历  

My Answer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 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) {
let res = 0;
if(!root) return res;

let dfs = (node,_deep)=>{
if(!!node){
if(_deep>res) res = _deep;
dfs(node.left,_deep+1);
dfs(node.right,_deep+1);
}
}

dfs(root,1);
return res;
};
CATALOG
  1. 1. LeetCode算法笔记-Day52
    1. 1.1. 104. Maximum Depth of Binary Tree
    2. 1.2. Analyse:
      1. 1.2.1. DFS
      2. 1.2.2. My Answer: