Java Easy to Understand Level Order Traversal Solution


  • 0
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        StringBuilder res = new StringBuilder();
        while(!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node == null) {
                res.append("#,");
                continue;
            }
            res.append(node.val).append(",");
            queue.offer(node.left);
            queue.offer(node.right);
        }
        return res.toString();
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data.equals("#,")) return null;
        String[] cs = data.split(",");
        TreeNode root = new TreeNode(Integer.valueOf(cs[0]));
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        for (int i = 1; i < cs.length; i += 2) {
            TreeNode node = queue.poll();
            if (!cs[i].equals("#")) {
                node.left = new TreeNode(Integer.valueOf(cs[i]));
                queue.offer(node.left);
            }
            if (!cs[i + 1].equals("#")) {
                node.right = new TreeNode(Integer.valueOf(cs[i + 1]));
                queue.offer(node.right);
            }
        }
        return root;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.