luoheng
10/26/2019 - 3:51 AM

tree2str

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

import "strconv"

func tree2str(t *TreeNode) string {
    if t == nil {
        return ""
    }
    left, right := tree2str(t.Left), tree2str(t.Right)
    str := strconv.Itoa(t.Val)
    if left != "" || left == "" && right != "" {
        str += "(" + left + ")"
    }
    if right != "" {
        str += "(" + right + ")"
    }
    return str
}