Leetcode Note: Go - Construct String From Binary Tree

Construct String from Binary Tree - LeetCode
https://leetcode.com/problems/construct-string-from-binary-tree/

  • Go 言語で取り組んだメモ

所感

  • バイナリツリーを走査して規定のフォーマットに変換した string を return する

回答

Construct String from Binary Tree - LeetCode
https://leetcode.com/problems/construct-string-from-binary-tree/solution/

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func tree2str(root *TreeNode) string {
    if root == nil {
        return ""
    }
    
    if root.Left == nil && root.Right == nil {
        return strconv.Itoa(root.Val) + ""
    }
    
    if root.Right == nil {
        return strconv.Itoa(root.Val) + "(" + tree2str(root.Left) + ")"
    }
    
    return strconv.Itoa(root.Val) + "(" + tree2str(root.Left) + ")(" + tree2str(root.Right) + ")"
}
  • 再帰で文字列成形を実装する