Swift solution - Recursive


  • 0
    class Solution {
        func tree2str(_ t: TreeNode?) -> String {
            guard let t = t else {
                return ""
            }
            
            let left = tree2str(t.left)
            let right = tree2str(t.right)
            var result = ""
    
            if left == "" && right == "" {
                result = String(t.val)
            } else if left == "" {
                result = String(t.val) + "()" + "(" + right + ")"
            } else if right == "" {
                result = String(t.val) + "(" + left + ")"
            } else {
                result = String(t.val) + "(" + left + ")" + "(" + right + ")"
            }
            
            return result
        }
    }
    

Log in to reply
 

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