[LeetCode] 606. Construct String from Binary Tree

Chobby·2026년 5월 11일

LeetCode

목록 보기
1067/1077

😎풀이

  1. 두 자식이 모두 존재할 경우, 재귀적으로 괄호로 감싸 트리 문자열 반환
  2. 좌측 자식만 존재할 경우, 좌측 트리만 재귀적으로 괄호로 감싸 트리 문자열 반환
  3. 우측 자식만 존재할 경우, 빈 괄호로 좌측 트리를 비우고, 우측 트리만 재귀적으로 감싸 트리 문자열 반환
  4. 최종 트리 문자열 반환
function tree2str(root: TreeNode | null): string {
    if(!root) return ''
    let str = `${root.val}`
    if(root.left && root.right) {
        str += `(${tree2str(root.left)})`
        str += `(${tree2str(root.right)})`
    } else if(root.left) {
        str += `(${tree2str(root.left)})`
    } else if(root.right) {
        str += '()'
        str += `(${tree2str(root.right)})`
    }
    return str
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글