HTMLify
LeetCode - Construct String from Binary Tree - Python
Views: 3 | Author: abh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # 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 # @leet start class Solution: def tree2str(self, root: TreeNode | None) -> str: if not root: return "" s = str(root.val) if root.left: s += "(" + self.tree2str(root.left) + ")" if not root.left and root.right: s += "()(" + self.tree2str(root.right) + ")" if root.left and root.right: s += "(" + self.tree2str(root.right) + ")" return s # @leet end |