상세 컨텐츠

본문 제목

104. Maximum Depth of Binary Tree

IT/Leetcode

by 마니씨 2023. 11. 18. 17:51

본문

Maximum Depth of Binary Tree - LeetCode

주어진 이진 트리의 최대 깊이를 반환하세요. 이진 트리의 최대 깊이는 루트 노드부터 가장 먼 리프 노드까지의 경로에 있는 노드 수입니다.

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

 

문제요약

 주어진 이진 트리의 최대 깊이를 구해야 합니다.

 

풀이과정

주어진 이진 트리의 최대 깊이를 찾기 위해 재귀적으로 트리의 깊이를 계산할 수 있습니다. 루트 노드부터 시작하며, 왼쪽 서브트리와 오른쪽 서브트리 중 더 깊은 쪽을 선택하여 깊이를 계산합니다.

  1. 주어진 루트 노드가 null인 경우, 트리의 깊이는 0입니다.
  2. 아니면, 왼쪽 서브트리와 오른쪽 서브트리의 깊이를 계산하고, 그 중 더 깊은 쪽에 1을 더하여 현재 노드를 포함한 깊이를 반환합니다.
  3. 이를 재귀적으로 모든 노드에 대해 반복하면 최대 깊이를 찾을 수 있습니다

이를 재귀적으로 모든 노드에 대해 반복하면 최대 깊이를 찾을 수 있습니다

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;

        int lDept = maxDepth(root.left);
        int rDept = maxDepth(root.right);
        
        return Math.max(lDept, rDept) + 1;
    }
}

'IT > Leetcode' 카테고리의 다른 글

394. Decode String  (0) 2023.11.18

관련글 더보기