BM39 序列化二叉树

层序遍历思想

import java.util.*;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    //创建一个无效的数值,用于标识空的叶子节点
    int INF = 0xfffff;
    //创建一个空节点用于存储无效的数值
    TreeNode emptyNode = new TreeNode(INF);
    String Serialize(TreeNode root) {
        if(root == null) {
            return "";
        }

        /**
         * 采用层序遍历的思想
         */
        Queue queue = new LinkedList<>();
        TreeNode treeNode = root;
        queue.offer(treeNode);

        StringBuilder builder = new StringBuilder();


        while (!queue.isEmpty()) {
            TreeNode poll = queue.poll();
            builder.append(poll.val+",");

            //只会存储叶子节点的左右空节点,不会再把空节点继续存储到队列中
            if (!poll.equals(emptyNode)) {
                queue.add((poll.left != null) ? poll.left:emptyNode);
                queue.add((poll.right != null) ? poll.right:emptyNode);
            }
        }

        return builder.toString();
    }


    TreeNode Deserialize(String str) {
        if (str.equals("")) {
            return null;
        }

        //根据逗号把数值分割成,字符串数组
        String[] strings = str.split(",");
        int lenSize = strings.length;
        //创建一个头结点
        TreeNode root = new TreeNode(Integer.parseInt(strings[0]));

        //创建队列并将头结点入队
        Queue queue = new LinkedList<>();
        queue.offer(root);

        /**
         * i从1开始,每次必须判断两个值
         * lenSize - 1是因为i+1恰好是最后一个元素的时候,
         * i +=2是因为每次两个元素要判断,每次跳跃两个元素
         */
        for (int i = 1; i < lenSize - 1; i +=2) {
            TreeNode poll = queue.poll();
            int a = Integer.parseInt(strings[i]);
            int b = Integer.parseInt(strings[i+1]);

            if (a != INF) {
                poll.left = new TreeNode(a);
                queue.offer(poll.left);
            }

            if (b != INF) {
                poll.right = new TreeNode(b);
                queue.offer(poll.right);
            }
        }
        return root;
    }
}

你可能感兴趣的:(二叉树,数据结构)