【发布时间】:2020-08-27 14:09:07
【问题描述】:
我正在尝试解决以下算法问题:
你需要用前序遍历的方式从二叉树中构造一个由括号和整数组成的字符串。
空节点需要用空括号对“()”表示。并且需要省略所有不影响字符串与原二叉树一一映射关系的空括号对。
示例 1: 输入:二叉树:[1,2,3,4]
1
/ \
2 3
/
4
输出:“1(2(4))(3)”
解释:原来需要是“1(2(4)())(3()())”, 但是您需要省略所有不必要的空括号对。 它将是“1(2(4))(3)”。
示例 2: 输入:二叉树:[1,2,3,null,4]
1
/ \
2 3
\
4
输出:“1(2()(4))(3)”
解释:和第一个例子差不多, 除了我们不能省略第一个括号对来打破输入和输出之间的一对一映射关系。
我写了以下代码:
class TreeNode {
constructor(val, left, right) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
}
const tree2str = (t) => {
const result = []
const stack = []
const dfs = (current) => {
if (current === null) return
result.push(current.val)
if (!current.left && current.right) result.push('(')
if (current.left) {
result.push('(')
stack.push(')')
dfs(current.left)
}
while (stack.length) {
result.push(stack.pop())
}
if (!current.left && current.right) stack.push(')')
if (current.right) {
result.push('(')
stack.push(')')
dfs(current.right)
}
}
dfs(t)
return result.join('')
}
到目前为止我的测试用例:
const tree = new TreeNode(1, new TreeNode(2, new TreeNode(4)), new TreeNode(3))
const tree2 = new TreeNode(1, new TreeNode(2, null, new TreeNode(4)), new TreeNode(3))
const tree3 = new TreeNode(1, new TreeNode(2, new TreeNode(3), new TreeNode(4)))
console.log(tree2str(tree)) // "1(2(4)())(3()())" ==> "1(2(4))(3)"
console.log(tree2str(tree2)) // "1(2()(4))(3)"
console.log(tree2str(tree3)) // "1(2(3)(4))" instead got "1(2(3))(4)"
只有两个工作,然而,我在第三个工作中遇到了问题,并且无法发现我哪里出错了。
【问题讨论】:
-
为什么必须用
while (stack.length)清空整个堆栈?也就是说,你为什么需要stack?return val + "(" + recurse(left) + ")(" + recurse(right + ")";
标签: javascript arrays stack binary-tree depth-first-search