My concise solutiuon


  • 0
    D

    '''
    public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) {
            return "#";
        }
        return (root.val + " " + serialize(root.left) + " " +serialize(root.right));
        
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data == null || data.length() == 0) {
            return null;
        }
        String[] nodes = data.split(" ");
        int[] index = {0};
        TreeNode root = deserializeHelper(nodes, index);
        return root;
    }
    private TreeNode deserializeHelper(String[] nodes, int[] index) {
        if (nodes[index[0]].equals("#")) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.valueOf(nodes[index[0]]));
        index[0]++;
        root.left = deserializeHelper(nodes, index);
        index[0]++;
        root.right = deserializeHelper(nodes, index);
        return root;
    }
    

    }
    ''''


Log in to reply
 

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