반응형
SMALL
문제
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
Constraints:
- The number of nodes in the tree is in the range [0, 104].
- -100 <= Node.val <= 100
코드
// BFS
var maxDepth = function(root) {
if(!root) return 0;
const queue = [root];
let max = 0;
while(queue.length) {
max = max + 1
const length = queue.length;
for(let i = 0; i < length; i++) {
if(queue[i].left) queue.push(queue[i].left);
if(queue[i].right) queue.push(queue[i].right);
}
queue.splice(0, length);
}
return max
};
// DFS
var maxDepth = function(root) {
if (!root) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};
반응형
LIST
'Coding Interview' 카테고리의 다른 글
[LeetCode] DFS - 130. Surrounded Regions (0) | 2022.09.27 |
---|---|
[LeetCode] DFS - 94. Binary Tree Inorder Traversal (0) | 2022.09.27 |
[LeetCode] BFS 210. Course Schedule II (feat. 위상정렬) (0) | 2022.09.26 |
[LeetCode] DFS 101. Symmetric Tree (0) | 2022.09.26 |
[LeetCode] DFS 98. Validate Binary Search Tree (0) | 2022.09.26 |