Efficient Java Solution (Leveraging Pre-Order traversal)


  • 0
    C
    public class Codec {
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if(root==null)
                return null;
            StringBuilder sb = new StringBuilder();
            preOrder(root, sb);
            String result =sb.toString().substring(1);
            
            System.out.println(result);
            return result;
        }
        void preOrder(TreeNode root, StringBuilder sb){
            if(root==null){
                sb.append(",null");
                return;
            }
            sb.append(",").append(root.val);
            preOrder(root.left, sb);
            preOrder(root.right, sb);
            
        }
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if(data==null)
                return null;
            int[] prefix = {0};
            String[] arr = data.split(",");
            TreeNode root = helper(arr,prefix);
            return root;
        }
        
        public TreeNode helper(String[] arr, int[] prefix){
            
            TreeNode root = new TreeNode(Integer.parseInt(arr[prefix[0]]));
            prefix[0]++;
            if(arr[prefix[0]].equals("null")){
                root.left=null;
            }else{
            root.left = helper(arr, prefix);
            }
            prefix[0]++;
            if(arr[prefix[0]].equals("null")){
                root.right=null;
            }else{
            root.right = helper(arr, prefix);
            }
            return root;
        }
    }

  • 0
    D

    why int[] instead of a simple 'int' counter?


Log in to reply
 

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