PreOrder Serialization using StringBuilder


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

  • 0
    W

    array to pass by reference shows how Java sometimes misses the point!


Log in to reply
 

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