[LeetCode] Maximum Depth of Binary Tree

2025. 2. 27. 15:00·공부/코딩테스트 | 알고리즘

문제

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.

 

예시

Input: root = [3,9,20,null,null,15,7]
Output: 3

Input: root = [1,null,2]
Output: 2

 


풀기

트리의 최대 깊이를 찾아내는 문제로 나는 DFS를 통해 풀어야겠다고 생각했다.

BFS를 통해서 풀 수도 있다고 함.

 

백준에서 배열에다 값을 넣어 풀어보기만 했지 LeetCode의 주어진 클래스 TreeNode를 어떻게 활용할지 몰라서 이번에도 이런 부분은 GPT 도움을 좀 받았다.

 

LeetCode 문제를 풀어본지 얼마 안된 나 같은 사람들을 위해 아래 코드도 첨부ㅋㅋ...ㅠ..

fun main() {
    val root = TreeNode(3)

    root.left = TreeNode(9)
    root.right = TreeNode(20)

    root.right?.left = TreeNode(15)
    root.right?.right = TreeNode(7)
}

class TreeNode(
    var `val`: Int
) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}

 

예제 1번에 해당하는 값을 넣는 코드이다.


결과

DFS는 재귀를 활용하고 BFS는 큐를 활용한다.

근데 난 DFS로 풀었으니 BFS는 그냥 스킵했다.

 

class Solution {
    fun maxDepth(root: TreeNode?): Int {
        when (root == null) {
            true -> return 0
            false -> return 1 + maxOf(maxDepth(root.left), maxDepth(root.right))
        }
    }
}

 

답은 위와 같다.

'공부 > 코딩테스트 | 알고리즘' 카테고리의 다른 글

[프로그래머스] 전력망을 둘로 나누기 (kotlin)  (0) 2025.03.11
[LeetCode] Validate Binary Search Tree  (1) 2025.03.01
[LeetCode] Min Stack  (0) 2025.02.26
[LeetCode] House Robber  (0) 2025.02.25
[LeetCode] Maximum Subarray  (0) 2025.02.24
'공부/코딩테스트 | 알고리즘' 카테고리의 다른 글
  • [프로그래머스] 전력망을 둘로 나누기 (kotlin)
  • [LeetCode] Validate Binary Search Tree
  • [LeetCode] Min Stack
  • [LeetCode] House Robber
나는 유찌
나는 유찌
쩌리쨩
  • 나는 유찌
    유찌 개발 일기
    나는 유찌
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 사이드 프로젝트
        • 게시판
        • 블로그(Spring boot + React.js ..
      • 데이터베이스
        • SQLD
      • 이슈 해결
      • Front
        • Javascript
        • Vue.js
        • HTML+CSS
      • Backend
        • Spring
        • ORM
        • JAVA
      • 공부
        • HTTP
        • OOP
        • 이것저것
        • 코딩테스트 | 알고리즘
      • Computer Science
        • Computer architecture
        • 데이터베이스
        • 운영체제
      • 일상
        • 독서
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Spring Boot
    jwt
    mssql
    추리소설
    LeetCode
    AccessDecisionVoter
    AntPathMatcher
    phantom read
    히가시노 게이고
    권한 scope 처리
    jwt 로그인 구현
    spring 격리수준
    Kotlin AntPathMatcher
    웹 개발
    독서
    role scope
    Spring Security AccessDecisionManager
    refresh token
    Access Token Refresh Token
    DIRTY READ
    pessimisticlock
    JWT이란?
    access token
    spring
    mysql 격리수준
    한국소설
    Access token 재발급
    Spring boot에서 JWT 구현
    redis 분산락
    Kotlin AccessDecisionManager
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
나는 유찌
[LeetCode] Maximum Depth of Binary Tree
상단으로

티스토리툴바