728x90
문제
재귀, 트리 문제이다.
binary tree의 root가 주어질 때, 최대 깊이를 구하는 문제이다.
https://leetcode.com/problems/maximum-depth-of-binary-tree/
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
풀이
root node에는 left node와 right node가 있다.
root의 maximum depth는 left/right node의 maximum depth 중 더 큰 값에 +1을 하면 된다.
위와 같은 경우, right node의 depth가 더 크기 때문에 그 값(2)에 1을 더한 것이 된다.
따라서, 재귀 호출을 활용하여 풀어내면 된다.
코드
public class leetcode_104 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
else
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
728x90
'알고리즘 문제풀이 > LeetCode' 카테고리의 다른 글
[LeetCode] 226. Invert Binary Tree (0) | 2021.07.05 |
---|---|
[LeetCode] 100. Same Tree (0) | 2021.07.05 |
[LeetCode] 70. Climbing Stairs (0) | 2021.06.10 |
[LeetCode] 322. Coin Change (1) | 2021.06.10 |
[LeetCode] 238. Product of Array Except Self (0) | 2021.06.06 |