给你二叉树的根节点 root ,请你采用前序遍历的方式,将二叉树转化为一个由括号和整数组成的字符串,返回构造出的字符串。
空节点使用一对空括号对 “()” 表示,转化后需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.
Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
示例 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
我们可以使用递归的方法得到二叉树的前序遍历,并在递归时加上额外的括号
- 如果当前节点没有孩子,那我们不需要在节点后面加上任何括号;
- 如果当前节点只有左孩子,那我们在递归时,只需要在左孩子的结果外加上一层括号,而不需要给右孩子加上任何括号;
- 如果当前节点有两个孩子,那我们在递归时,需要在两个孩子的结果外都加上一层括号;
- 如果当前节点只有右孩子,那我们在递归时,需要先加上一层空的括号 ‘()’ 表示左孩子为空,再对右孩子进行递归,并在结果外加上一层括号。
第三步和第四步情况一样,如果左孩子为空,(左孩子)等同于()
var tree2str = function (root) {
if (!root) return ""
if (!root.left && !root.right) {
return "" + root.val
}
if (!root.right) {
return root.val + "(" + tree2str(root.left) + ")"
}
return root.val + "(" + tree2str(root.left) + ")(" + tree2str(root.right) + ")"
};
leetcode:https://leetcode-cn.com/problems/construct-string-from-binary-tree/