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


求解代码

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

相关推荐
Charlie_lll4 分钟前
力扣解题-移动零
后端·算法·leetcode
iAkuya1 小时前
(leetcode)力扣100 62N皇后问题 (普通回溯(使用set存储),位运算回溯)
算法·leetcode·职场和发展
YuTaoShao6 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
TracyCoder1238 小时前
LeetCode Hot100(27/100)——94. 二叉树的中序遍历
算法·leetcode
草履虫建模14 小时前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
VT.馒头19 小时前
【力扣】2721. 并行执行异步函数
前端·javascript·算法·leetcode·typescript
不穿格子的程序员1 天前
从零开始写算法——普通数组篇:缺失的第一个正数
算法·leetcode·哈希算法
VT.馒头1 天前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
执着2591 天前
力扣hot100 - 108、将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
52Hz1181 天前
力扣230.二叉搜索树中第k小的元素、199.二叉树的右视图、114.二叉树展开为链表
python·算法·leetcode