Maximum Depth of Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
//이런식으로 재귀 코드를 작성하고 생각하는 것이 더 쉽기 때문에 핸들러 함수를 사용
var maxDepth = function(root) {
//깊이의 정의 때문에 숫자/깊이 값 1에서 시작
return maxDepthHandler(root,1)
};
//빈 root가 있으면 tree에는 아무것도 없으로 0깊이로 반환한다
var maxDepthHandler = function(root, num){
if(root == null){
return 0
}
if (root.right == null && root.left == null){
return num
}
//Math.max를 사용하여 두 루트 깊이에서 가장 높은 값을 얻는다.
//나머지 코드 부분은 개별 루트 케이스를 처리
if (root.right && root.left){
return Math.max( maxDepthHandler(root.right, num+1), maxDepthHandler(root.left, num + 1))
} else if (root.right != null){
return maxDepthHandler(root.right, num+1)
} else {
return maxDepthHandler(root.left, num+1)
}
};
|
cs |
'알고리즘 > 문제풀이' 카테고리의 다른 글
10주차 알고리즘 풀이 (0) | 2021.10.23 |
---|---|
프로그래머스 모의고사 javascript (0) | 2021.08.21 |
프로그래머스) K번째 수 Javascript (0) | 2021.08.20 |
hash(level2) - 위장 (0) | 2021.08.14 |
완주하지 못한 선수 JS, javascript (0) | 2021.08.14 |