【基础算法】二叉树的按层遍历序列化与反序列化

本文详细介绍了如何实现二叉树的层次遍历序列化,即将二叉树转化为水平顺序的字符串表示,以及如何进行反序列化,将字符串还原为原来的二叉树结构。通过深度优先搜索和广度优先搜索两种方法,阐述了关键步骤和注意事项,适合初学者理解二叉树操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package test;

import java.util.LinkedList;
import java.util.Queue;

public class SeriaByLevel {
    //  按层遍历二叉树的方式序列化
    public static String binToStr(Node head) {
        StringBuilder stringBuilder = new StringBuilder();
        Queue<Node> queue = new LinkedList<>();
        Node nNode = null;
        queue.offer(head);
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            if (node != null) {
                stringBuilder.append(node.val+"!");
            }
            else {
                stringBuilder.append("#!");
                continue;
            }
            if (node.left != null) {
                queue.offer(node.left);
            }
            else {
                queue.offer(nNode);
            }
            if (node.right != null){
                queue.offer(node.right);
            }
            else {
                queue.offer(nNode);
            }
        }
        return stringBuilder.toString();
    }
    //    按层遍历二叉树的方式反序列化
    public static Node strToQueCeng(String string) {
        Queue<Node> queue = new LinkedList<>();
        String values[] = string.split("!");
        int index = 0;
        Node head = new Node(Integer.valueOf(values[index++]));
        queue.offer(head);
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            node.left = getNewNode(values[index ++]);
            node.right = getNewNode(values[index ++]);
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return head;
    }

    public static Node getNewNode(String val) {
        if (val.equals("#")) {
            return null;
        }
        else {
            return new Node(Integer.valueOf(val));
        }
    }
// 按层遍历二叉树
    public static void nodePrint (Node head) {
        Node last = head;
        Node nlast = head;
        Queue<Node> queue = new LinkedList<>();
        queue.offer(head);
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            System.out.print(node.val);
            System.out.print("\t");
            if (node.left != null) {
                queue.offer(node.left);
                nlast = node.left;
            }
            if (node.right != null) {
                queue.offer(node.right);
                nlast = node.right;
            }
            if (last == node) {
                System.out.println();
                last = nlast;
            }
        }
    }

    //    测试
    public static void main(String[] args) {
        Node n1 = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);
        Node n4 = new Node(4);
        Node n5 = new Node(5);
        Node n6 = new Node(6);
        Node n7 = new Node(7);
        Node n8 = new Node(8);

        n1.left = n2;
        n1.right = n3;
        n2.left = n4;
        n3.left = n5;
        n3.right = n6;
        n5.left = n7;
        n5.right = n8;
//测试序列化
        String string = binToStr(n1);
        System.out.println(string);
// 测试反序列化
        Node head = strToQueCeng(string);
        nodePrint(head);
    }
}
class Node {
    Node left;
    Node right;
    int val;
    public Node () {}
    public Node (int val) {
        this.val = val;
    }
}

在C语言中,我们可以利用二叉树的特性来从中序遍历和后序遍历序列重构原始二叉树,然后采用广度优先搜索(BFS)的方式输出其遍历序列。以下是基本步骤: 1. 分析输入: - 中序遍历:左 -> 根 -> 右 - 后序遍历:左 -> 右 -> 根 2. 中序遍历构建根节点: - 中序遍历的第一个元素是根节点,因为它是所有节点中最左侧的。 3. 使用后序遍历重建左右子树: - 后序遍历的第一个和第二个元素通常是左子树,最后一个元素是右子树。 - 对于当前的左子树,继续处理后两个元素并重复上述过程。 4. 递归构建子树: - 用中序遍历剩余部分(跳过已找到的根节点),作为下一次查找根节点时的左侧元素。 - 使用后序遍历剩下的部分,找到当前子树的结束点,并以此为基础重建右侧子树。 5. 输出遍历: - 使用队列实现BFS,将根节点放入队列,然后不断取出队首节点并将其子节点加入队列,直到队列为空。 下面是简单的伪代码示例: ```c void buildTree(int* inorder, int* postorder, int start, int end) { if (start > end) return; // 找到中序遍历的根节点 int rootVal = inorder[start]; int rootIndex = search(postorder, rootVal); // 构建左子树和右子树 buildTree(inorder, postorder, start + 1, rootIndex - 1); buildTree(inorder, postorder, rootIndex + 1, end); // 将根节点插入遍历队列 enqueue(queue, rootVal); } void printLevelOrder() { // 初始化队列 queue = createQueue(); // 使用中序遍历和后序遍历构造二叉树,然后输出遍历 // ... } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值