Java 14ms DFS solution, short, clean, and easy understand


  • 0
    F
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
    	StringBuilder s = new StringBuilder();
    	helperS(root, s);
    	return s.toString();
    }
    
    private void helperS(TreeNode root, StringBuilder s) {
    	if (root == null) {
    		s.append("#");
    		return;
    	}
    	s.append(root.val);
    	s.append(",");
    	helperS(root.left, s);
    	s.append(",");
    	helperS(root.right, s);
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
    	String[] sa = data.split(",");
    	int[] index = new int[1];
    	return helperD(sa, index);
    }
    
    private TreeNode helperD(String[] sa, int[] index) {
    	if (sa[index[0]].equals("#"))
    		return null;
    	TreeNode t = new TreeNode(Integer.valueOf(sa[index[0]]));
    	index[0]++;
    	t.left = helperD(sa, index);
    	index[0]++;
    	t.right = helperD(sa, index);
    	return t;
    }

Log in to reply
 

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