Easy Java Solution using level order traversal


  • 0
    A
            StringBuffer sb = new StringBuffer();
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while(!queue.isEmpty()){
                TreeNode node = queue.poll();
                if(sb.length()>0){
                    sb.append(",");
                }
                if(node==null){
                    sb.append("null");
                    continue;
                }else{
                    sb.append(node.val);
                }
                queue.add(node.left);
                queue.add(node.right);
            }
            
           // System.out.println(sb.toString());
            return sb.toString();
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            String val[] = data.split(",");
            TreeNode treeNode[] = new TreeNode[val.length];
            TreeNode root = null;
            for(int i=0;i<val.length;i++){
                if(val[i].equals("null") && i==0){
                    return root;
                }else{
                    if(val[i].equals("null")){
                        treeNode[i] = null;
                    }else{
                        treeNode[i] = new TreeNode(Integer.valueOf(val[i]));    
                    }
                    
                    
                }
            }
            int adj=0;
            for(int i=0;i<treeNode.length;i++){
                if(i==0){
                    root=treeNode[i];
                }
                if(null!=treeNode[i]){
                    int l = i*2+1-adj;
                    int r = i*2+2-adj;
                    if(l<treeNode.length){
                        treeNode[i].left = treeNode[l];
                    }
                    if(r<treeNode.length){
                        treeNode[i].right = treeNode[r];
                    }
                }else{
                    adj += 2;
                }
                 
            }
            return root;
        }```

Log in to reply
 

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