难度:简单
https://leetcode-cn.com/problems/construct-string-from-binary-tree/
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
空节点则用一对空括号 "()"
表示。而且你需要省略所有不影响字符串与原始二叉树之间
的一对一映射关系的空括号对。
输入: 二叉树: [1,2,3,4]
1
/ \
2 3
/
4
输出: "1(2(4))(3)"
解释: 原本将是“1(2(4)())(3())”,
在你省略所有不必要的空括号对之后,
它将是“1(2(4))(3)”。
输入: 二叉树: [1,2,3,null,4]
1
/ \
2 3
\
4
输出: "1(2()(4))(3)"
解释: 和第一个示例相似,
除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。
/**
* 递归
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param root~
* @returns
*/
export function tree2str(root: TreeNode | null): string {
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)})`;
}
/**
* 迭代
* @desc 时间复杂度 O(N) 空间复杂度 O(N)
* @param root
* @returns
*/
export function tree2str2(root: TreeNode | null): string {
if (!root) return '';
let result = '';
const stack = [root];
const visited = new Set<TreeNode>();
while (stack.length) {
const node = stack[stack.length - 1];
if (visited.has(node)) {
if (node !== root) result += ')';
stack.pop();
} else {
visited.add(node);
if (node !== root) result += '(';
result += '' + node.val;
if (!node.left && node.right) result += '()';
node.right && stack.push(node.right);
node.left && stack.push(node.left);
}
}
return result;
}