https://leetcode.com/problems/maximum-depth-of-binary-tree/
LeetCode - The World's Leading Online Programming Learning Platform
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
트리를 구현이 가능한지 불가능한지를 판단할 수 있는 기본 문제
제시해준 TreeNode를 사용하여 재귀함수로 풀이하였습니다.
우선 깊이는 1부터 시작하구요. (문제 예시를 보면 알 수 있음)
루트 노드를 기준으로 왼쪽, 오른쪽을 재귀함수를 돌리면
재귀함수가 도는 만큼 각 노드를 기준으로 자식 노드를 가지고 있다는 것을 의미합니다.
왼쪽, 오른쪽으로 내려가서 각각 자식 노드를 파악하는데 있어서
왼쪽 오른쪽이 다른 깊이를 가지고 있을 수 있기 때문에 max 를 사용
(예제처럼 루트노드를 기준으로 왼쪽노드는 깊이가 1이고, 오른쪽은 3)
깊이 시작은 1이라고 했으니 return 1 + max(left, right) = maximum depth
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
if root == nil {
return 0
} else {
var left = maxDepth(root?.left)
var right = maxDepth(root?.right)
return 1 + max(left, right)
}
}
}
'알고리즘' 카테고리의 다른 글
Swift로 정렬 알고리즘 정리하기 ... 1 (0) | 2024.06.19 |
---|---|
백준 24511 - Swift (0) | 2024.06.17 |
LeetCode - 236. Lowest Common Ancestor of a Binary Tree (Swift) (0) | 2024.02.08 |
백준 1181 - Swift (1) | 2024.02.05 |
LeetCode - 160. Intersection of Two Linked Lists (Swift) (0) | 2024.01.19 |