package leetcode;

/**
 * https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/
 */
public class Problem1028 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode recoverFromPreorder(String S) {
        // TODO
        return null;
    }

    public static void main(String[] args) {
        Problem1028 prob = new Problem1028();
        System.out.println(prob.recoverFromPreorder("1-2--3--4-5--6--7"));
        System.out.println(prob.recoverFromPreorder("1-2--3---4-5--6---7"));
        System.out.println(prob.recoverFromPreorder("1-401--349---90--88"));
    }
}

@@ -348,34 +348,119 @@
     
-// TODO
+return recoverFromPreorder(S, new IntRef(), 0);
 %0A    
+%7D%0A%0A
     
-return nul
+private static class IntRef %7B%0A        private int va
 l;%0A 
@@ -470,29 +470,30 @@
 %7D%0A%0A    p
-ublic
+rivate
  static 
 void mai
@@ -488,308 +488,745 @@
 tic 
-void main(String%5B%5D args) %7B%0A        Problem1028 prob = new Problem1028();%0A        System.out.println(prob.recoverFromPreorder(%221-2--3--4-5--6--7%22));%0A        System.out.println(prob.recoverFromPreorder(%221-2--3---4-5--6---7%22));%0A        System.out.println(prob.recoverFromPreorder(%221-401--349---90--88%22))
+TreeNode recoverFromPreorder(String s, IntRef idx, int depth) %7B%0A        if (idx.val == s.length()) %7B%0A            return null;%0A        %7D%0A        int i = idx.val;%0A        int count = 0;%0A        while (i %3C s.length() && s.charAt(i) == '-') %7B%0A            count++;%0A            i++;%0A        %7D%0A        String num = %22%22;%0A        while (i %3C s.length() && Character.isDigit(s.charAt(i))) %7B%0A            num += s.charAt(i);%0A            i++;%0A        %7D%0A        TreeNode node = null;%0A        if (count == depth) %7B%0A            node = new TreeNode(Integer.parseInt(num));%0A            idx.val = i;%0A            node.left = recoverFromPreorder(s, idx, depth + 1);%0A            node.right = recoverFromPreorder(s, idx, depth + 1);%0A        %7D%0A        return node
 ;%0A  

Solve problem 1028