Java DFS+queue solution


  • 1
    D
    public class Codec {
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if (root == null) return "$,";
            return root.val + "," + serialize(root.left) + serialize(root.right);
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            Queue<String> q = new LinkedList<>();
            String[] strs = data.split(",");
            for (String str : strs) {
                q.add(str);
            }
            return dfs(q);
        }
        
        private TreeNode dfs(Queue<String> q) {
            String str = q.remove();
            if (str.equals("$")) return null;
            TreeNode root = new TreeNode(Integer.valueOf(str));
            root.left = dfs(q);
            root.right = dfs(q);
            return root;
        }
    }

  • 0
    N

    This is an excellent solution, very clean and well formed, easy to follow. Thank you.


Log in to reply
 

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