Sword refers to offer 37. Serialized binary tree

Sword refers to offer 37. Serialized binary tree

Title description

Insert picture description here

Problem-solving ideas

Preorder traversal

public class Codec {
    
    

    String SEP = ",";    //分割符
    String NULL = "#";   //空指针

    // Encodes a tree to a single string.
    //定义:将以root为根节点的二叉树序列化为 "2,#,#,"的形式
    public String serialize(TreeNode root) {
    
    
         if (root == null) {
    
    
             return NULL + SEP;
         }
         return root.val + SEP + serialize(root.left) + serialize(root.right);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
    
    
        String[] splitData = data.split(SEP);
        LinkedList<String> nodes = new LinkedList<>();
        for (String s : splitData) {
    
    
            nodes.add(s);
        }
        return deserialize(nodes);
    }

    //辅助函数,反序列化二叉树,并输出反序列化后的结果
    public TreeNode deserialize(LinkedList<String> nodes) {
    
    
        if (nodes.isEmpty()) return null;
        //前序遍历的第一个节点就是根节点
        String firstNode = nodes.removeFirst();
        //如果是空节点,则直接返回
        if (firstNode.equals(NULL)) return null;
        TreeNode root = new TreeNode(Integer.parseInt(firstNode));
        //先构造左子树,等左子树全部remove后,剩下的就是右子树,继续构造右子树
        //去除root节点后,node中第一个节点是左子树的根节点,所以先构造左子树 */
        root.left = deserialize(nodes);
        root.right = deserialize(nodes);
        return root;
    }

}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

Guess you like

Origin blog.csdn.net/cys975900334/article/details/115254296