剑指Offer——序列化二叉树

1、题目描述

  请实现两个函数,分别用来序列化和反序列化二叉树

2、代码实现

package com.baozi.offer;

/**
 * 请实现两个函数,分别用来序列化和反序列化二叉树
 *
 * @author BaoZi
 * @create 2019-07-15-9:43
 */
public class Offer30 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(0);
        TreeNode t1 = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        TreeNode t3 = new TreeNode(3);
        TreeNode t4 = new TreeNode(4);
        TreeNode t5 = new TreeNode(5);
        TreeNode t6 = new TreeNode(6);
        TreeNode t7 = new TreeNode(7);
        root.left = t1;
        root.right = t2;
        t1.left = t3;
        t1.right = t4;
        t2.left = t5;
        t2.right = t6;
        t5.right = t7;
        Offer30 offer30 = new Offer30();
        String serialize = offer30.Serialize(root);
        System.out.println(serialize);
    }

    //序列化
    String Serialize(TreeNode root) {
        if (root == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        Serialize1(root, sb);
        return sb.toString();
    }

    private void Serialize1(TreeNode root, StringBuffer sb) {
        //在序列化的过程中碰见某一节点的左子树或者右子树为空的时候,需要进行特别的标记并返回
        if (root == null) {
            sb.append("*");
            return;
        }
        //遇到正常节点的时候,把该节点的值保存下来并且设置一个分隔符
        sb.append(root.val);
        sb.append("#");
        Serialize1(root.left, sb);
        Serialize1(root.right, sb);
    }

    //反序列化
    TreeNode Deserialize(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        //进行反序列化的时候需要把字符串按照序列化的时候的分隔符拆分成字符串数组
        String[] strings = str.split("#");
        return Deserialize1(strings);
    }

    //因为要进行递归的使用该方法不断的得到某一个节点的左右子树,所以表示字符串数组指针的索引值只能是一个全局变量
    int index = -1;

    private TreeNode Deserialize1(String[] strings) {
        index++;
        if (!strings[index].equals("*")) {
            TreeNode temp = new TreeNode(-1);
            temp.val = Integer.parseInt(strings[index]);
            temp.left = Deserialize1(strings);
            temp.right = Deserialize1(strings);
            return temp;
        }
        return null;
    }
}

  

posted @ 2019-07-15 10:05  包子的百草园  阅读(196)  评论(0编辑  收藏  举报