1372. Longest ZigZag Path in a Binary Tree

양성준·2025년 6월 2일

코딩테스트

목록 보기
74/102

문제

https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/description/

풀이

class Solution {
    int max = 0;
    public int longestZigZag(TreeNode root) {
        DFS(root.left, 1, "left");
        DFS(root.right, 1, "right");
        return max;  
    }
    
    public void DFS(TreeNode node, int length, String direction) {
        if(node == null) {
            return;
        }
        max = Math.max(max, length);

        if(direction.equals("right")) {
            DFS(node.left, length + 1, "left");
            DFS(node.right, 1, "right");
        } else {
            DFS(node.right, length + 1, "right");
            DFS(node.left, 1, "left");
        }
    }
}
  • right으로 왔다면, left를 탐색 / left로 왔다면 right로 탐색
    • 지그재그로 가다가 더이상 안되면, 길이 1로 새로 시작
profile
백엔드 개발자

0개의 댓글