题目
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair “()”. And you need to omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.
Example 1:
Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4
Output: “1(2(4))(3)”
Explanation: Originallay it needs to be “1(2(4)())(3()())”,
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be “1(2(4))(3)”.
Example 2:
Input: Binary tree: [1,2,3,null,4]
1
/ \
2 3
\
4
Output: “1(2()(4))(3)”
Explanation: Almost the same as the first example,
except we can’t omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
解题思路
- 前序遍历二叉树,并输出节点的值
- 遍历的过程中所有非空左右子树需要加上圆括号
- 如果右子树为空,则圆括号忽略,左子树为空,圆括号不能忽略
代码
tree2Str.go
package _606_Construct_String_from_Binary_Tree
import "fmt"
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func PreOrder(t *TreeNode, ret *string) {
if nil == t {
return
}
(*ret) += fmt.Sprintf("(%+v", t.Val)
if nil == t.Left && nil != t.Right {
(*ret) += "()"
}
PreOrder(t.Left, ret)
PreOrder(t.Right, ret)
(*ret) += ")"
}
func Tree2str(t *TreeNode) string {
if nil == t {
return ""
}
var ret string
ret += fmt.Sprintf("%+v", t.Val)
if nil == t.Left && nil != t.Right {
ret += "()"
}
PreOrder(t.Left, &ret)
PreOrder(t.Right, &ret)
return ret
}
测试
tree2Str_test.go
package _606_Construct_String_from_Binary_Tree
import "testing"
func InitNode(val int, left *TreeNode, right *TreeNode) (ret *TreeNode){
ret = new(TreeNode)
ret.Val = val
ret.Left = left
ret.Right = right
return ret
}
func TestTree2str(t *testing.T) {
l3_1 := InitNode(4, nil, nil)
l2_1 := InitNode(2, l3_1, nil)
l2_2 := InitNode(3, nil, nil)
input := InitNode(1, l2_1, l2_2)
ret1 := Tree2str(input)
want1 := "1(2(4))(3)"
if ret1 == want1 {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", want1, ret1)
}
r3_1 := InitNode(4, nil, nil)
r2_1 := InitNode(2, nil, r3_1)
r2_2 := InitNode(3, nil, nil)
input2 := InitNode(1, r2_1, r2_2)
ret2 := Tree2str(input2)
want2 := "1(2()(4))(3)"
if ret2 == want2 {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", want2, ret2)
}
w6 := InitNode(6, nil, nil)
w5 := InitNode(5, nil, w6)
w4 := InitNode(4, nil, w5)
w3 := InitNode(3, nil, w4)
w2 := InitNode(2, nil, w3)
input3 := InitNode(1, nil, w2)
ret3 := Tree2str(input3)
want3 := "1()(2()(3()(4()(5()(6)))))"
if ret3 == want3 {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", want3, ret3)
}
}