[LeetCode] Diameter of Binary Tree

아르당·2026년 1월 27일

LeetCode

목록 보기
114/136
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

이진 트리 root가 주어졌을 때, 트리의 지름의 길이를 반환해라.
이진 트리의 지름은 트리의 임의의 두 노드 사이의 가장 긴 경로의 길이이다. 이 경로는 루트를 통화할 수도 있고 통과하지 않을 수도 있다.
두 노드 사이의 경로 길이는 두 노드 사이의 간선 수로 나타낸다.

Example

#1

Input: root = [1, 2, 3, 4, 5]
Output: 3
Explanation: 3은 [4, 2, 1, 3] 또는 [5, 2, 1, 3] 경로의 길이이다.

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

Constraints

  • 트리에 있는 노드의 숫자는 [1, 10^4] 범위 내에 있다.
  • -100 <= Node.val <= 100

Solved

/**
 * Definition for a binary tree node.
 * 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;
 *     }
 * }
 */
class Solution {
    int result = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        dfs(root);

        return result;
    }

    private int dfs(TreeNode root){
        if(root == null){
            return 0;
        }

        int l = dfs(root.left);
        int r = dfs(root.right);

        result = Math.max(result, l + r);

        return 1 + Math.max(l, r);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글