zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【根据二叉树创建字符串(606-java)】

JAVA二叉树 创建 字符串 根据
2023-09-27 14:29:28 时间

根据二叉树创建字符串(606-java)

你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。

空节点则用一对空括号 “()” 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。

示例 1:

输入: 二叉树: [1,2,3,4]
1
/
2 3
/
4

输出: “1(2(4))(3)”

解释: 原本将是“1(2(4)())(3())”,
在你省略所有不必要的空括号对之后,
它将是“1(2(4))(3)”。

public class LC263_606_tree2str {
    //二叉树  前序遍历
    public static String tree2str(TreeNode root) {
        //递归+前序遍历
        StringBuilder sb = new StringBuilder();
        dfs(root, sb);
        return sb.toString();
    }

    private static void dfs(TreeNode root, StringBuilder sb) {
        if (root == null) {
            return;
        }
        sb.append(root.val);
        if (root.left != null) {
            sb.append("(");
            dfs(root.left, sb);
            sb.append(")");
        }
        if (root.left == null && root.right != null) {
            sb.append("(");
            sb.append(")");
        }
        if (root.right != null) {
            sb.append("(");
            dfs(root.right, sb);
            sb.append(")");
        }
    }

    public static void main(String[] args) {
        String s = tree2str(TreeNode.createTree());
        System.out.println(s);
    }
}