序列化和反序列化BST

来源:互联网 发布:audacity mac 汉化 编辑:程序博客网 时间:2024/06/05 15:26
  • 1 序列化:

    • 参考上一篇博客提到的前序遍历二叉树的方法,不难得出序列化BST的方法。
    • 其实就是通过前序遍历,将遍历到的节点依次存到字符串里面。
  • 2反序列化

    • 先将待反序列化的字符串内的元素按顺序存到队列内;
    • 将跟节点设为队列的头元素;
    • 遍历队列,找到大于根节点的元素,并以此为分界,分别递归调用队列的左区间和右区间;
    • 左区间返回的值作为跟节点的左孩子,右边返回的值作为根节点的右孩子。

代码实现如下:

public class Codec {    private static final String NULL = "null";    //序列化    public String serialize(TreeNode root) {        StringBuilder sb = new StringBuilder();        if (root == null) return NULL;        Stack<TreeNode> stack = new Stack<>();        while (!stack.isEmpty() || root != null) {            if (root != null) {                stack.push(root);                sb.append(root.val).append(",");                root = root.left;            } else {                root = stack.pop().right;            }        }        return sb.toString();    }    //反序列化    public TreeNode deserialize(String data) {        if (data == NULL) return null;        String[] s = data.split(",");        Queue<Integer> queue = new LinkedList<>();        for (String e : s) {            queue.offer(Integer.parseInt(e));        }        return getRoot(queue);    }    private TreeNode getRoot(Queue<Integer> queue) {        if (queue.isEmpty()) {            return null;        }        TreeNode root = new TreeNode(queue.poll());        Queue<Integer> subQueue = new LinkedList<>();        while (!queue.isEmpty() && queue.peek() < root.val) {            subQueue.offer(queue.poll());        }        root.left = getRoot(subQueue);        root.right = getRoot(queue);        return root;    }}
原创粉丝点击