Why my code got stack overflow error on the longest test case?


  • 0
    H
    public static String serialize(TreeNode root) {
    	if (root == null) {
    		return "";
    	}
    	StringBuilder sb = new StringBuilder();
    	Queue<TreeNode> q = new LinkedList<TreeNode>();
    	q.add(root);
    	while (!q.isEmpty()) {
    		int size = q.size();
    		for (int i = 0; i < size; i++) {
    			TreeNode node = q.poll();
    			if(node == null){
    				sb.append("null,");
    				continue;
    			}else{
    				sb.append(node.val).append(",");
    			}
    			if(node.right != null){
    				q.offer(node.left);
    				q.offer(node.right);
    			}else{
    				if(node.left != null){
    					q.offer(node.left);
    				}
    			}
    		}
    	}
    	sb.delete(sb.length() - 1, sb.length());
    	return sb.toString();
    }
    
    // Decodes your encoded data to tree.
    static int start = 0;
    
    public static TreeNode deserialize(String data) {
    	if (data.length() == 0) {
    		return null;
    	}
    	String[] strings = data.split(",");
    	return des(strings);
    }
    
    public static TreeNode des(String[] strings) {
    	if (start >= strings.length) {
    		return null;
    	}
    	String s = strings[start];
    	int val = 0;
    	if (s.equals("null")) {
    		return null;
    	} else {
    		val = Integer.valueOf(s);//it said error happen here
    	}
    	TreeNode root = new TreeNode(val);
    	start++;
    	root.left = des(strings);
    	start++;
    	root.right = des(strings);
    	return root;
    }

Log in to reply
 

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