[LeetCode] 623. Add One Row to Tree (Daily Question)
문제
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일때 새로 생성한 노드가 루트 노드가 된다는 것인데, 처음에는 함수 로직에 어떻게든 포함시키려 했으나, 따로 예외처리하는 편이 훨씬 편하겠다는 생각이 들어 바꾸었고, 그러길 잘했다고 생각한다.