Notice
Recent Posts
Recent Comments
Link
복's
[ LeetCode - 104 ] Maximum Depth of Binary Tree 본문
728x90
https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
Maximum Depth of Binary Tree - LeetCode
Can you solve this real interview question? Maximum Depth of Binary Tree - 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
leetcode.com
문제 보자마자 DFS로 풀려고 했으나 LeetCode는 tree가 주어지기 때문에 주어진대로 풀었다 근데 사실 DFS로 풀었다고 봐도 무방한거 같다.
결국 leaf node까지 내려갔다가 끝 지점에 도착해서야 다른 곳 지역을 서치하니까
[ 📌 풀이 ]
left, right 순서 상관없이 한 쪽으로 계속해서 파고 들어 가면서 depth의 max 값을 갱신하는 방법이다.
사실 지금까지 풀었던 tree문제와 매우 유사하지만 요구 사항만 다르다.
순회 방법은 전위, 중위, 후위 어떤 방법으로 해도 풀리는 문제라서 상관 없을거 같다.
[ 📌 코드 - Python ]
"""
# Author : Lee In Bok
# Date : 2023.12.01(Fri)
# Spend Time: 04m 26s
# Runtime : 35 ms (Beats 97.39%)
# Memory : 18.9 MB (Beats 6.48%)
# Algoritm : Tree
"""
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
max_depth = 0
if not root:
return 0
def order(depth, root):
nonlocal max_depth
max_depth = max(depth, max_depth)
if root:
if root.left:
order(depth + 1, root.left)
if root.right:
order(depth + 1, root.right)
order(1, root)
return max_depth
[ 📌 코드 - Java ]
/**
* Author : Lee In Bok
* Date : 2023.12.01(Fri)
* Spend Time: 04m 26s
* Runtime : 0 ms (Beats 100%)
* Memory : 41.9 MB (Beats 23.92%)
* Algoritm : Tree
*/
class Solution {
int max = 0;
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
order(1, root);
return max;
}
public void order(int depth, TreeNode root){
max = Math.max(depth, max);
if(root != null){
if(root.left != null){
order(depth + 1, root.left);
}
if(root.right != null){
order(depth + 1, root.right);
}
}
}
}
[ 📌 결과 - Python ]
[ 📌 결과 - Java ]
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[ LeetCode - 182 ] Duplicate Emails (0) | 2023.12.01 |
---|---|
[ LeetCode - 1189 ] Maximum Number of Balloons (1) | 2023.11.26 |
[ LeetCode - 180 ] Consecutive Numbers (0) | 2023.11.25 |
[ LeetCode - 178 ] Rank Scores (2) | 2023.11.20 |
[ LeetCode - 176 ] Second Highest Salary (1) | 2023.11.18 |