Java Solution


  • 0
    R
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Codec {
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if(root == null)
                return null;
            
            LinkedList<TreeNode> q = new LinkedList<>();
            q.addLast(root);
            
            StringBuilder res = new StringBuilder();
            while(!q.isEmpty()) {
                TreeNode temp = q.removeFirst();
                if(temp == null)
                    res.append("X,");
                else {
                    res.append(temp.val + ",");
                    q.addLast(temp.left);
                    q.addLast(temp.right);
                }
            }
            
            res.deleteCharAt(res.length() - 1);
            return res.toString();
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
          	if (data == null)
    			return null;
    
    		String a[] = data.split(",");
    		TreeNode root = new TreeNode(Integer.parseInt(a[0]));
    
    		LinkedList<TreeNode> q = new LinkedList<>();
    		q.addLast(root);
    
    		for (int i = 1; i < a.length; i++) {
    			TreeNode temp = q.removeFirst();
    			if (!a[i].equals("X")) {
    				temp.left = new TreeNode(Integer.parseInt(a[i]));
    				q.addLast(temp.left);
    			}
    
    			if (!a[++i].equals("X")) {
    				temp.right = new TreeNode(Integer.parseInt(a[i]));
    				q.addLast(temp.right);
    			}
    		}
    		return root;
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.deserialize(codec.serialize(root));
    

Log in to reply
 

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