【层序遍历】序列化二叉树


求解代码

java 复制代码
String Serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        if (root != null) {
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            sb.append(root.val + ","); // 先存入根节点值

            while (!queue.isEmpty()) {
                root = queue.poll(); // 取出队首的待处理节点

                // 严格先处理左孩子:有值存值+逗号,无值存# +逗号
                if (root.left != null) {
                    sb.append(root.left.val + ",");
                    queue.add(root.left);
                } else {
                    sb.append("#,");
                }

                // 严格后处理右孩子:有值存值+逗号,无值存# +逗号
                if (root.right != null) {
                    sb.append(root.right.val + ",");
                    queue.add(root.right);
                } else {
                    sb.append("#,");
                }
            }
        }
        return sb.toString();
    }


    TreeNode Deserialize(String str) {
        if (str.equals("")) {
            return null;
        }
        String[] nodes = str.split(","); // 按分隔符拆分出所有节点内容
        int index = 0;
        TreeNode root = generate(nodes[index++]); // 第一个元素是根节点
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll(); // 取出待分配子节点的父节点
            cur.left = generate(nodes[index++]); // 严格先分配左孩子
            cur.right = generate(nodes[index++]); // 严格后分配右孩子

            // 只有非空节点才有子节点,需要入队等待分配子节点
            if (cur.left != null) queue.add(cur.left);
            if (cur.right != null) queue.add(cur.right);
        }
        return root;
    }

    TreeNode generate(String val) {
        return val.equals("#") ? null : new TreeNode(Integer.parseInt(val));
    }

小贴士:

Integer.parseInt () 和 Integer.valueOf ()

这俩都是 Java 中把「数字格式的字符串」转为整数 的核心静态方法,最核心的区别只有一个:

✅ Integer.parseInt(String s) → 返回 基本数据类型 int

✅ Integer.valueOf(String s) → 返回 包装类对象 Integer

相关推荐
文丑颜不良啊1 天前
LeetCode2261~2280题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2241~2260题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2321~2340题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z2 天前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
文丑颜不良啊2 天前
LeetCode2161~2180题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2141~2160题目解析
java·leetcode
Dream it possible!3 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊3 天前
算法之双指针系列(一)
算法·leetcode
Pniubi3 天前
力扣560.和为k的子数组
算法·leetcode·职场和发展