leetcode 606. 根据二叉树创建字符串

题解

递归遍历,无效的括号包含两种情况,节点左右子树为空 或 节点右子树为空

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func tree2str(t *TreeNode) string {
if t == nil {
return ""
}
if t.Left == nil && t.Right == nil {
return strconv.Itoa(t.Val)
}
if t.Right == nil {
return strconv.Itoa(t.Val) + "(" + tree2str(t.Left) + ")"
}
return strconv.Itoa(t.Val) + "(" + tree2str(t.Left) + ")" + "(" + tree2str(t.Right) + ")"
}