[LeetCode] 1372. Longest ZigZag Path in a Binary Tree, Medium

2025. 4. 25. 13:53·CodingTest/LeetCode
반응형

1. 문제

  • 이진 트리가 주어질 때, 노드가 좌 우 반복하면서 이어지는 경로의 최대 길이를 구하라.

2. 해결

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function longestZigZag(root: TreeNode | null): number {
    let maxLength = 0;

    function DFS(node: TreeNode | null, direction: 'L' | 'R', length: number) {
        if (!node) return;

        maxLength = Math.max(maxLength, length);

        DFS(node.left, 'L', direction === 'R' ? length + 1 : 1);
        DFS(node.right, 'R', direction === 'L' ? length + 1 : 1);
    }

    if (root.left) DFS(root.left, 'L', 1); // 왼쪽으로 시작
    if (root.right) DFS(root.right, 'R', 1); // 오른쪽으로 시작

    return maxLength;
}
  • 전달되는 direction에 따라 길이를 증가시키며 최대 길이를 갱신한다.
  • 처음에는 bottom up으로 접근했는데, 잘 안풀렸다.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 1161. Maximum Level Sum of a Binary Tree, Medium
  • [LeetCode] 199. Binary Tree Right Side View, Medium
  • [LeetCode] 437. Path Sum III, Medium
  • [LeetCode] 1448. Count Good Nodes in Binary Tree, Medium
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    medium
    boj2108
    알고리즘
    leetcode 2236
    next 14
    백준7576자바
    백준7576
    meidum
    Java
    백준1427
    BOJ
    자바
    프로그래머스
    백준1260
    boj1427
    백준
    백준2751
    component-scan
    Easy
    TypeScript
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 1372. Longest ZigZag Path in a Binary Tree, Medium
상단으로

티스토리툴바