606. 根据二叉树创建字符串
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
空节点则用一对空括号 "()" 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
示例 1:
输入: 二叉树: [1,2,3,4]
1
/
2 3
/
4
输出: "1(2(4))(3)"
解释: 原本将是“1(2(4)())(3())”,
在你省略所有不必要的空括号对之后,
它将是“1(2(4))(3)”。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-string-from-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public class Solution {
public String tree2str(TreeNode t) {
if (t == null)
return "";
if (t.left == null && t.right == null)
return t.val + "";
if (t.right == null)
return t.val + "(" + tree2str(t.left) + ")";
return t.val + "(" + tree2str(t.left) + ")(" + tree2str(t.right) + ")";
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号