二叉树的序列化

会递归遍历二叉树就会序列化。 

package TreeTest;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @ProjectName: zxh0125
 * @Package: TreeTest
 * @ClassName: SerializeTree
 * @Author: zxh
 * @Description: 序列化二叉树
 * @Date: 2022/1/24 12:09
 * @Version: 1.0
 */
/*
* 前中后序序列号就只是换一下位置!
* */
public class SerializeTree {

    public static Queue<String> preSerial(TreeNode head) {
        Queue<String> ans = new LinkedList<>();
        pres(head, ans);
        return ans;
    }

    public static void pres(TreeNode head, Queue<String> ans) {
        if (head == null) {
            return;
        }
        ans.add(head.val + "");
        pres(head.left, ans);
        pres(head.right, ans);
    }

    public static TreeNode buildByPreQueue(Queue<String> ans) {
        if (ans == null || ans.size() == 0) {
            return null;
        }
        return preb(ans);
    }

    public static TreeNode preb(Queue<String> ans){
        String value = ans.poll();
        if(value == null){
            return null;
        }
        TreeNode head = new TreeNode(Integer.parseInt(value));
        head.left = preb(ans);
        head.right = preb(ans);
        return head;
    }

}

上一篇:Kubernetes(K8s) kubectl rolling-update 常用命令


下一篇:C# 开源一个基于 yarp 的 API 网关 Demo,支持绑定 Kubernetes Service