LeetCode 297번째: 두 갈래 나무의 서열화와 반서열화(앞의 서열 반복)

1653 단어
주소:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
Java 코드:
import java.util.LinkedList;
import java.util.Queue;

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) {
            return "";
        }

        StringBuilder stringBuilder = new StringBuilder();
        dfs(root, stringBuilder);
        return stringBuilder.toString();
    }

    private void dfs(TreeNode node, StringBuilder stringBuilder) {
        if (node == null) {
            stringBuilder.append("#").append(",");
            return;
        }

        stringBuilder.append(node.val).append(",");
        dfs(node.left, stringBuilder);
        dfs(node.right, stringBuilder);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        //  
        if (data.length() == 0) {
            return null;
        }

        //  ,  ""  ,  [""]
        String[] split = data.split(",");
        Queue queue = new LinkedList<>();
        for (String str : split) {
            queue.offer(str);
        }
        return dfs(queue);
    }

    private TreeNode dfs(Queue queue) {
        if (queue.isEmpty()) {
            return null;
        }
        String head = queue.poll();
        if ("#".equals(head)) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(head));
        root.left = dfs(queue);
        root.right = dfs(queue);
        return root;
    }
}

좋은 웹페이지 즐겨찾기