My much simpler recursive solution beats 97%


  • 0
    M
    public class Codec {
        int pos = 0;
        
        public String serialize(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            buildToString(root, sb);
            return sb.toString();
        }
        private void buildToString(TreeNode node, StringBuilder sb) {
            if (node == null) sb.append("X,");
            else {
                sb.append(node.val).append(",");
                buildToString(node.left, sb);
                buildToString(node.right, sb);
            }
        }
        
        public TreeNode deserialize(String data) {
            String[] d = data.split(",");
            return buildToTree(d);
        }
        
        private TreeNode buildToTree(String[] data) {
            if (data[pos].equals("X")) {
                pos++;
                return null;
            }else {
                TreeNode node = new TreeNode(Integer.valueOf(data[pos++]));
                node.left = buildToTree(data);
                node.right = buildToTree(data);
                return node;
            }
        }
    }
    

Log in to reply
 

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