My simple and clear Java solution


  • 0
    K
    /**
     * 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) {
            StringBuffer sb = new StringBuffer();
            order(root, sb);
            return sb.toString();
        }
        
        private void order(TreeNode root, StringBuffer sb) {
            if (root == null) {
                sb.append(-1 + ",");
                return;
            }
            sb.append(root.val + ",");
            order(root.left, sb);
            order(root.right, sb);
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            String[] strs = data.split(",");
            int[] nums = new int[strs.length];
            for (int i = 0; i < nums.length; i++) {
                nums[i] = Integer.valueOf(strs[i]);
            }
            TreeNode root = toTree(nums, new Index(0));
            return root;
        }
        
        private TreeNode toTree(int[] nums, Index id) {
            if (nums.length == id.i || nums[id.i] == -1) {
                return null;
            }
            TreeNode node = new TreeNode(nums[id.i]);
            id.i++;
            node.left = toTree(nums, id);
            id.i++;
            node.right = toTree(nums, id);
            return node;
        }
        
        class Index {
            int i;
            
            public Index(int i) {
                this.i = i;
            }
        }
    }
    
    // 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.