Simple Java Method with clear null value detection


  • 0
    T
    public class Codec {
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            if(null == root)
                return new String(sb);
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            sb.append(root.val+",");
            while(!queue.isEmpty()) {
                TreeNode node = queue.remove();
                if(node.left != null) {
                    queue.add(node.left);
                    sb.append(node.left.val+",");
                } else {
                    sb.append("#,");
                }
                if(node.right != null) {
                    queue.add(node.right);
                    sb.append(node.right.val+",");
                } else {
                    sb.append("#,");
                }
            }
            sb.deleteCharAt(sb.length()-1);
            return new String(sb);
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if(null == data || data.length() < 1)
                return null;
            String[] ss = data.split(",");
            int i = 0;
            Queue<TreeNode> queue = new LinkedList<>();
            TreeNode root = new TreeNode(Integer.parseInt(ss[i]));
            queue.add(root);
            i++;
            while(!queue.isEmpty()) {
                TreeNode cur = queue.remove();
                if(i < ss.length) {
                    if(ss[i].equals("#")) {
                        cur.left = null;
                    } else {
                        TreeNode left = new TreeNode(Integer.parseInt(ss[i]));
                        cur.left = left;
                        queue.add(left);
                    }
                    i++;
                }
                if(i < ss.length) {
                    if(ss[i].equals("#")) {
                        cur.right = null;
                    } else {
                        TreeNode right = new TreeNode(Integer.parseInt(ss[i]));
                        cur.right = right;
                        queue.add(right);
                    }
                    i++;
                }
            }
            return root;
        }
    }
    

Log in to reply
 

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