The blog for Design Patterns, Linux, HA and Myself!

06
September 2020

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

Loading Comments...

- All Elements in Two Binary Search Trees Solution
- Construct Binary Search Tree From Preorder Traversal Solution
- Maximum Binary Tree Solution
- Sum of Nodes With Even Valued Grandparent Solution
- Deepest Leaves Sum Solution
- Symmetric Tree or Mirror Tree Solution
- Diameter of Binary Tree Solution
- Binary Tree Paths Solution
- Cousins in Binary Tree Solution
- Sum of Left Leaves Solution
- Same Tree or Equal Tree Solution
- Minimum Absolute Difference in BST Solution
- Construct String From Binary Tree Solution - Leetcode
- Two Sum IV - Input is a BST Solution - Leetcode
- Convert BST to Greater Tree Solution - Leetcode
- Convert Sorted Array to Binary Search Tree Solution
- Average of Levels in Binary Tree Solution
- Leaf Similar Trees Solution - Leetcode
- Sum of Root to Leaf Binary Numbers - Leetcode
- Univalued Binary Tree - Leetcode
- Maximum Depth of N Ary Tree - Leetcode
- Increasing Order Search Tree - Leetcode
- Merge Two Binary Trees Solution
- Range Sum of BST - Leetcode