Problem Solving/LeetCode
2023.12.10 Today's Challenge
fabichoi
2023. 12. 10. 23:45
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(')')
반응형