Java Solution using BFS


  • 0
    C
    // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            
            while(!queue.isEmpty()){
                TreeNode top = queue.poll();
                if(top == null){
                    sb.append("#,");
                }
                else{
                    sb.append(top.val + ",");
                    queue.add(top.left);
                    queue.add(top.right);
                }
            }
            
            return sb.toString();
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if(data.isEmpty() || data.charAt(0) == '#'){
                return null;
            }
            
            String[] arr = data.split(",");
            int idx = 0;
            
            TreeNode root = new TreeNode(Integer.valueOf(arr[0]));
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            
            while(!queue.isEmpty()){
                TreeNode top = queue.poll();
                if(top == null){
                    continue;
                }
                
                top.left = arr[++idx].equals("#") ? null : new TreeNode(Integer.valueOf(arr[idx]));
                top.right = arr[++idx].equals("#") ? null : new TreeNode(Integer.valueOf(arr[idx]));
                queue.add(top.left);
                queue.add(top.right);
            }
            
            return root;
        }
    

Log in to reply
 

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