SeangG
def _(): _()
SeangG
전체 방문자
오늘
어제
  • 분류 전체보기 (37)
    • Programming Language (0)
      • Python (0)
      • Web (0)
    • Algorithm (34)
    • Art (0)
      • 3D Modeling (0)
      • Pixel (0)
      • Picture (0)
    • Game (0)
    • Project (3)
      • Problems (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 매핑 테이블
  • Leecode
  • string
  • dfs
  • 문자열
  • 로마 숫자
  • Python
  • Daily Question
  • LeedCode
  • Tree
  • react.js
  • next.js
  • Queue
  • Fast Refresh
  • BFS
  • graph
  • github oauth
  • leetcode
  • WSL
  • spring boot

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
SeangG
Algorithm

[LeetCode] 623. Add One Row to Tree (Daily Question)

[LeetCode] 623. Add One Row to Tree (Daily Question)
Algorithm

[LeetCode] 623. Add One Row to Tree (Daily Question)

2024. 4. 16. 10:47

문제


 

Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.

Note that the root node is at depth 1.

The adding rule is:
    - Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
    - cur's original left subtree should be the left subtree of the new left subtree root.
    - cur's original right subtree should be the right subtree of the new right subtree root.
    - If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.

 

root(트리), val, depth가 주어졌을 때 depth깊이의 노드에 val의 값을 가진 노드를 끼워넣는 문제이다.

 

Example 1:
Input: root = [4,2,6,3,1,5], val = 1, depth = 2
Output: [4,1,1,2,null,null,6,3,1,5]

Example 2:
Input: root = [4,2,null,3,1], val = 1, depth = 3
Output: [4,2,null,1,1,3,null,null,1]

 

풀이


아이디어

DFS로 depth에 도달하면 노드를 새로 생성해 끼워 넣는다.

 

코드

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def search(self, node: Optional[TreeNode], depth: int) -> None:

        # 목표 깊이에 도달하면 현재 노드의 자식 사이에 새로운 노드 추가
        if depth == self.depth:
            node.left = TreeNode(self.val, node.left, None)
            node.right = TreeNode(self.val, None, node.right)

        # 도달하지 못했다면 더 깊이 탐색
        else:
            if node.left:
                self.search(node.left, depth+1)
            if node.right:
                self.search(node.right, depth+1)
            

    def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:
        self.depth = depth
        self.val = val

        # 깊이가 1인 경우 루트노드 새로 생성
        if depth == 1:
            root = TreeNode(self.val, root, None)
        else:
            self.search(root, 2)

        return root

 

후기


난이도

문제 이해와 아이디어를 떠올리는 것은 쉬웠으나, 구현에서 조금 헷갈렸다.객체를 이용한 문제는 LeetCode에서 처음 접했기에 아직 객체구조의 트리를 다루는게 익숙하지 않은 것 같다.

 

예외사항은 depth가 1일때 새로 생성한 노드가 루트 노드가 된다는 것인데, 처음에는 함수 로직에 어떻게든 포함시키려 했으나, 따로 예외처리하는 편이 훨씬 편하겠다는 생각이 들어 바꾸었고, 그러길 잘했다고 생각한다.

 

 

'Algorithm' 카테고리의 다른 글

[LeetCode] 463. Island Perimeter (Daily Question)  (1) 2024.04.18
[LeetCode] 988. Smallest String Starting From Leaf (Daily Question)  (0) 2024.04.17
[LeetCode] 129. Sum Root to Leaf Numbers (Daily Question)  (0) 2024.04.15
[LeetCode] 404. Sum of Left Leaves (Daily Question)  (0) 2024.04.15
[LeetCode] 85. Maximal Rectangle (Daily Question)  (0) 2024.04.13
  • 문제
  •  
  • 풀이
  •  
  • 후기
'Algorithm' 카테고리의 다른 글
  • [LeetCode] 463. Island Perimeter (Daily Question)
  • [LeetCode] 988. Smallest String Starting From Leaf (Daily Question)
  • [LeetCode] 129. Sum Root to Leaf Numbers (Daily Question)
  • [LeetCode] 404. Sum of Left Leaves (Daily Question)
SeangG
SeangG

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.