😎풀이

  1. 트리 높이를 구해줄 헬퍼 함수 getTreeHeight 정의
  2. 트리 높이에 따라 문제 공식에 맞게 m, n 선언 후 res 보드 생성
  3. root 부터 재귀적으로 전위 순회하며, 각 노드의 적절 위치 표시
  4. 시각화 된 res 반환
function printTree(root: TreeNode | null): string[][] {
    if(!root) return [[""]]
    const height = getTreeHeight(root) - 1
    const m = height + 1
    const n = Math.pow(2, height + 1) - 1
    const res = Array.from({ length: m }, () => Array(n).fill(""))
    const col = Math.floor((n - 1) / 2)
    function dfs(node: TreeNode | null, y: number, x: number) {
        if(!node) return
        res[y][x] = String(node.val)
        const pos = Math.pow(2, height - y - 1)
        dfs(node.left, y + 1, x - pos)
        dfs(node.right, y + 1, x + pos)
    }
    dfs(root, 0, col)
    return res
};

function getTreeHeight(node: TreeNode | null) {
    if(!node) return 0
    return 1 + Math.max(getTreeHeight(node.left), getTreeHeight(node.right))
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글