每日一题 为了工作 2020 0423 第五十二题

/**
 *
 * 【题目】
 * 二叉树被记录成文件的过程叫作二叉树的序列化, 通过文件内容重建原来二叉树的过
 * 程叫作二叉树的反序列化。给定一棵二叉树的头节点head, 并已知二叉树节点值的类型为
 * 32位整型。请设计一种二叉树序列化的方案, 并用代码实现。
 * 【解法】
 * 通过先序遍历实现序列化和反序列化。
 * 先介绍先序遍历下的序列化过程,首先假设序列化的结果字符串为str, 初始时str=""。
 * 先序遍历二叉树, 如果遇到null节点, 就在str的末尾加上"#!", "#"表示这个节点为空,
 * 节点值不存在, "!"表示一个值的结束; 如果遇到不为空的节点, 假设节点值为3, 就在
 * str的末尾加上"3!"。
 *
 * @author 雪瞳
 * @Slogan 时钟尚且前行,人怎能再此止步!
 * @Function 实现二叉树的序列化
 *
 */

  

public class SerivalTree {

    public static String servialTree(Node head){
        if (head == null){
            return "#!";
        }
        String res = head.value+"!";
        res += servialTree(head.left);
        res += servialTree(head.right);

        return res;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        Node left = new Node(2);
        Node right = new Node(3);

        head.right = right;
        head.left = left;
        String result = servialTree(head);
        System.out.println(result);
    }
}
class Node{
    public int value;
    public Node right;
    public Node left;
    public Node(int data){
        this.value = data;
    }
}

  

 

 

猜你喜欢

转载自www.cnblogs.com/walxt/p/12759984.html