반응형
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으로 접근했는데, 잘 안풀렸다.