天机阁

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

2022-07-09 · 2 min read
LeetCode

题目

给你二叉树的根节点 root ,请你采用前序遍历的方式,将二叉树转化为一个由括号和整数组成的字符串,返回构造出的字符串。

空节点使用一对空括号对 "()" 表示,转化后需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。

难度:🌟🌟

示例 1:

输入:root = [1,2,3,4]
输出:"1(2(4))(3)"
解释:初步转化后得到 "1(2(4)())(3()())" ,但省略所有不必要的空括号对后,字符串应该是"1(2(4))(3)" 。

示例 2:

输入:root = [1,2,3,null,4]
输出:"1(2()(4))(3)"
解释:和第一个示例类似,但是无法省略第一个空括号对,否则会破坏输入与输出一一映射的关系。

提示:

  • 树中节点的数目范围是 [1, 104]
  • -1000 <= Node.val <= 1000

题解

根据题目描述,我们需要对左节点为空且右节点不为空的情况单独处理,即加 () 括号。
这题明显使用前序遍历方式,给前序遍历的节点加上括号即可。

代码实现

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func tree2str(root *TreeNode) (res string) {
	if root == nil {
		return
	}
	var preo func(node *TreeNode)
	preo = func(node *TreeNode) {

		res += fmt.Sprintf("%d", node.Val)

		if node.Left != nil {
			res += "("
			preo(node.Left)
			res += ")"
		}
		if node.Left == nil && node.Right != nil {
			res += "()"
		}
		if node.Right != nil {
			res += "("
			preo(node.Right)
			res += ")"
		}

		return
	}
	preo(root)
	return
}