数据结构和算法自我学习[0412]

217 阅读1分钟

前言

  • 博文为博主从新开始学习数据结构和算法的学习记录。
  • 请优先观看0409,声明清楚了题目和解法等出处。

今天的题目

  • 在二叉树中找到一个节点的后继节点
  • 序列化二叉树
  • 反序列化二叉树

在二叉树中找到一个节点的后继节点

**
     * 题目:在二叉树中找到一个节点的后继节点
     * 分析:根据有无右子树进行区分,若存在右子树,那么后续节点为右子树的最左节点
     * 若不存在右子树,需要向上找到第一个作为左子树的祖先节点
     *
     * @param node
     */
    private static void successorNode(Node node) {
        if (node == null) {
            return;
        }
        if (node.getRight() != null) {
            //存在,找到右树的最左节点
            Node currentNode = node.getRight();
            while (currentNode.getLeft() != null) {
                currentNode = currentNode.getLeft();
            }
            System.out.println(currentNode.getData());
            return;
        } else {
            //不存在右子树,向上查找
            Node parent = node.getParent();
            while (parent != null && parent.getLeft() != node) {
                //再向上
                node = parent;
                parent = node.getParent();
            }
            if (parent != null) {
                System.out.println(parent.getData());
            } else {
                System.out.println("不存在后继");
            }
            return;
        }
    }

序列化二叉树

/**
     * 题目:采用先序序列化二叉树,#代表空,_是分割
     * 注意:字符串分割出的数组是不包括分割号本身的
     * @param node
     * @return
     */
    private static String serialByPre(Node node) {
        StringBuilder str = new StringBuilder("");
        if (node == null) {
            return "#_";
        }
        str.append(node.getData() + "_");
        str.append(serialByPre(node.getLeft()));
        str.append(serialByPre(node.getRight()));
        return str.toString();
    }

反序列化二叉树

/**
     * 题目:反序列化二叉树
     * 分析:把先序序列化的进行反序列化,需要借组队列实现
     * @param string
     * @return
     */
    private static Node deserialization(String string) {
        if (string == null || string == "") {
            return null;
        }
        //把结果按照_分割
        String[] split = string.split("_");
        //需要进行先序反序列化
        //借助队列
        Deque<String> queue = new LinkedList<>();
        for (String str : split) {
            queue.offer(str);
        }
        Node node = deserialization(queue);
        return node;
    }

    private static Node deserialization(Deque queue) {
        if (queue.isEmpty()) {
            return null;
        }
        Node node = new Node(queue.poll());
        node.setLeft(deserialization(queue));
        node.setRight(deserialization(queue));
        return node;
    }