Python Solution using PreOrder traversal

  • 0
    def preOrder(root):
        string = '('
        string += str(root.val)
        if root.left:
            string += preOrder(root.left)
            if root.right:
                string += '()'
        if root.right:
            string += preOrder(root.right)
        string += ')'
        return string
    class Solution(object):
        def tree2str(self, t):
            if not t:
                return ''
            return preOrder(t)[1:-1]

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.