The blog for Design Patterns, Linux, HA and Myself!
In this article, we’ll be solving the problem: Construct String from Binary Tree.
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: Originally, 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.
To solve this problem, I’ll be using the pre order tree traversal approach once again. I’ll be using a buffer to append
the characters (
, )
and the node value.
Here is the code for that:
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func tree2str(t *TreeNode) string {
if t == nil {
return ""
}
return preOrder(t)
}
func preOrder(t *TreeNode) string {
var buffer bytes.Buffer
buffer.WriteString(strconv.Itoa(t.Val))
if t.Left == nil && t.Right == nil {
return buffer.String()
}
if t.Left != nil {
buffer.WriteString("(")
buffer.WriteString(preOrder(t.Left))
buffer.WriteString(")")
} else {
buffer.WriteString("()")
}
if t.Right != nil {
buffer.WriteString("(")
buffer.WriteString(preOrder(t.Right))
buffer.WriteString(")")
}
return buffer.String()
}
This program is available here @ GitHub as well