파비의 매일매일 공부기록

2023.12.10 Today's Challenge 본문

Problem Solving/LeetCode

2023.12.10 Today's Challenge

fabichoi 2023. 12. 10. 23:45

https://leetcode.com/problems/construct-string-from-binary-tree/?envType=daily-question&envId=2023-12-08

 

Construct String from Binary Tree - LeetCode

Can you solve this real interview question? Construct String from Binary Tree - Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty

leetcode.com

트리 활용한 문제

class Solution:
    def tree2str(self, root: Optional[TreeNode]) -> str:
        res = []
        self.dfs(root, res)
        return ''.join(res)

    def dfs(self, t, res):
        if t is None:
            return

        res.append(str(t.val))

        if not t.left and not t.right:
            return

        res.append('(')
        self.dfs(t.left, res)
        res.append(')')

        if t.right is not None:
            res.append('(')
            self.dfs(t.right, res)
            res.append(')')
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.12.12 Today's Challenge  (0) 2023.12.12
2023.12.11 Today's Challenge  (0) 2023.12.11
2023.12.09 Today's Challenge  (0) 2023.12.09
2023.12.08 Today's Challenge  (0) 2023.12.08
2023.12.07 Today's Challenge  (0) 2023.12.07
Comments