1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| // @Title: 根据二叉树创建字符串 (Construct String from Binary Tree)
// @Author: 15816537946@163.com
// @Date: 2022-03-19 17:30:09
// @Runtime: 12 ms
// @Memory: 9.5 MB
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func tree2str(root *TreeNode) string {
switch {
case root == nil:
return ""
case root.Left == nil && root.Right == nil:
return strconv.Itoa(root.Val)
case root.Right == nil:
return fmt.Sprintf("%d(%s)", root.Val, tree2str(root.Left))
default:
return fmt.Sprintf("%d(%s)(%s)", root.Val, tree2str(root.Left), tree2str(root.Right))
}
}
|