剑指 Offer 37. 序列化二叉树 java

题目:

剑指 Offer 37. 序列化二叉树
请实现两个函数,分别用来序列化和反序列化二叉树。
示例:
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5

序列化为 “[1,2,3,null,null,4,5]”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof

解题:

关键点:树的层次遍历

package com.example.algorithm.tree;

import lombok.Builder;
import lombok.Data;
/**
 * 树结构
 * @author meijia
 * @date 2020/10/29
 */
@Data
@Builder
public class TreeNode {
    Integer val;
    TreeNode left, right;
   
    public TreeNode() {}
    public TreeNode(Integer val) {
        this.val = val;
    }
    public TreeNode(Integer val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
    static TreeNode getTreeRoot() {
        TreeNode root = TreeNode.builder().val(1)
                .left(TreeNode.builder().val(2).build())
                .right(TreeNode.builder().val(3).build())
                .build();
        root.getLeft().setLeft(TreeNode.builder().val(4).build());
        root.getLeft().setRight(TreeNode.builder().val(5).build());
        root.getLeft().getRight().setLeft(TreeNode.builder().val(7).build());
        root.getLeft().getRight().setRight(TreeNode.builder().val(8).build());
        root.getRight().setRight(TreeNode.builder().val(6).build());
        return root;
    }
    // 初始化二叉排序树
    static TreeNode getSortTreeRoot() {
        TreeNode root = TreeNode.builder().val(8)
                .left(TreeNode.builder().val(2).build())
                .right(TreeNode.builder().val(9).build())
                .build();
        root.getLeft().setLeft(TreeNode.builder().val(1).build());
        root.getLeft().setRight(TreeNode.builder().val(5).build());
        root.getLeft().getRight().setLeft(TreeNode.builder().val(3).build());
        root.getLeft().getRight().setRight(TreeNode.builder().val(6).build());
        root.getRight().setRight(TreeNode.builder().val(10).build());
        return root;
    }
}

/**
 * 序列化,反序列化树
 *  序列化,树转为数组
 *  反序列化,数组转为树
 *  关键点:树的层次遍历
 *  特别注意的一点: 最后一排的子节点的null 也要全部输入哦
 *  [1,2,3,4,5,null,6,null,null,7,8,null,null,null,null,null,null]
 */
public class SerializeTree {

    public static void main(String[] args) {
        String result = serialize(TreeNode.getTreeRoot());
        System.out.println(result);
        TreeNode root = deserialize(result);
        traverse_level(root);
    }

    public static void traverse_level(TreeNode root) {
        if (root == null) {
            System.out.println("当前树是空的!");
        }
        LinkedList queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node != null) {
                System.out.print(node.val + "  ");
            }
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
    }

    // Encodes a tree to a single string.
    public static String serialize(TreeNode root) {
        if (root == null) {
            return "[]";
        }
        StringBuilder result = new StringBuilder("[");
        LinkedList queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node != null) {
                result.append(node.val).append(",");
                queue.offer(node.left);
                queue.offer(node.right);
            } else {
                result.append("null").append(",");
            }
        }
        result.deleteCharAt(result.length() - 1);
        return result.append("]").toString();
    }

    // Decodes your encoded data to tree.
    // 这里去构建树的时候,一定要注意的是,遍历的是数组,通过数组的下标和树的层次遍历来进行构建;
    // 当数组中的元素值 不是null的时候  说明当前节点还有左儿子或者右儿子,应该把儿子放入queue里面;
    // 当数组中的元素值 是null的时候  说明当前节点没有了左儿子或者右儿子,不需要进行构建了无需放入到queue里面;
    public static TreeNode deserialize(String data) {
        if ("[]".equals(data)) {
            return null;
        }
        String[] vals = data.substring(1, data.length() - 1).split(",");
        TreeNode root = new TreeNode(Integer.valueOf(vals[0]));

        int i = 1;
        LinkedList queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (!vals[i].equals("null")) { // 如果元素不为空,构建左节点 并放入queue;
                node.left = new TreeNode(Integer.valueOf(vals[i]));
                queue.offer(node.left);
            }
            i ++;
            if (!vals[i].equals("null")) {// 如果元素不为空,构建右节点 并放入queue;
                node.right = new TreeNode(Integer.valueOf(vals[i]));
                queue.offer(node.right);
            }
            i ++;
        }

        return root;
    }
}

你可能感兴趣的:(Leetcode-算法,java,二叉树)