前言
记录下leetcode每日一题
题目描述
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
空节点则用一对空括号 "()" 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
示例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)"
解释: 和第一个示例相似,
除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。
思路
- 首先判断当前遍历的节点是否为null,为null返回空
- 判断当前节点是否存在左右子树
- 左右子树都不存在,返回当前节点node的val
- 右子树不存在,递归遍历返回的左子树,在外面加上括号
- 遍历左子树,在外面加上括号。遍历右子树,外面加上括号
代码
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {string}
*/
var tree2str = function(root) {
if(root == null) return ''
if(!root.left && !root.right) {
return '' + root.val
}
if(root.right == null) {
return root.val + '(' + tree2str(root.left) + ')'
}
return root.val + '(' + tree2str(root.left) + ')(' + tree2str(root.right) + ")"
}
最后
每天进步一点点