티스토리 뷰
Problem
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
Solution
이진 트리의 루트 노드가 주어졌을 때 해당 트리의 최대 깊이를 구하는 문제입니다.
재귀호출을 이용해 간단히 구현할 수 있습니다.
package io.lcalmsky.leetcode.maximum_depth_of_binary_tree;
import io.lcalmsky.leetcode.TreeNode;
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
Test
package io.lcalmsky.leetcode.maximum_depth_of_binary_tree;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import io.lcalmsky.leetcode.TreeNode;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void testAll() {
assertAll(
() -> test(TreeNode.of(3, 9, 20, null, null, 15, 7), 3),
() -> test(TreeNode.of(1, null, 2), 2)
);
}
private void test(TreeNode given, int expected) {
// when
Solution solution = new Solution();
int actual = solution.maxDepth(given);
// then
assertEquals(expected, actual);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
136. Single Number (0) | 2022.02.25 |
---|---|
39. Combination Sum (0) | 2022.02.24 |
560. Subarray Sum Equals K (0) | 2022.02.19 |
454. 4Sum II (0) | 2022.02.18 |
23. Merge k Sorted Lists (0) | 2022.02.17 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 함께 자라기 후기
- Spring Data JPA
- gRPC
- 스프링부트
- 스프링 부트 튜토리얼
- Spring Boot Tutorial
- Jackson
- intellij
- spring boot application
- 알고리즘
- 함께 자라기
- spring boot app
- spring boot jwt
- Linux
- Spring Boot
- r
- 스프링 부트
- proto3
- JPA
- QueryDSL
- @ManyToOne
- 스프링 부트 회원 가입
- Java
- 스프링 부트 애플리케이션
- JSON
- 헥사고날 아키텍처
- Spring Boot JPA
- leetcode
- 클린 아키텍처
- 스프링 데이터 jpa
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 27 |
28 | 29 | 30 |
글 보관함