😎풀이

  1. depth가 1인경우 시작 root 노드를 바로 좌측 노드로 새 트리 생성
  2. 그렇지 않은 경우 root부터 깊이 우선 탐색하며, 특정 깊이가 되었을 때 TreeNode를 새로 생성하여 본래 leaf 노드를 할당
  3. depth에 새로 val이 추가된 TreeNode 반환
function addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode | null {
    if(depth === 1) {
        return new TreeNode(val, root, null)
    }
    function dfs(node: TreeNode | null, curDepth: number) {
        if(!node) return
        if(curDepth === depth - 1) {
            const originLeft = node.left
            const originRight = node.right
            node.left = new TreeNode(val, originLeft, null)
            node.right = new TreeNode(val, null, originRight)
            return
        }
        dfs(node.left, curDepth + 1)
        dfs(node.right, curDepth + 1)
    }
    dfs(root, 1)
    return root
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글