Java Recursive Solution


  • 0
    A
    class Solution {
        private static class Counter {
            private int value;
    
            public Counter() {
                this.value = 0;
            }
    
            public int increment(final int amout) {
                this.value += amout;
                return this.value;
            }
    
            public int increment() {
                return increment(1);
            }
    
            public int get() {
                return this.value;
            }
        }
    
        public TreeNode str2tree(final String s) {
            if (s.isEmpty()) {
                return null;
            }
            return str2treeHelper(s, new Counter());
        }
    
        private TreeNode str2treeHelper(final String s, final Counter counter) {
            if (counter.get() >= s.length()) {
                return null;
            } else {
                int value = parseInt(s, counter);
                TreeNode current = new TreeNode(value);
    
                if (counter.get() < s.length() && s.charAt(counter.get()) == '(') {
                    counter.increment();    // skip '('
                    current.left = str2treeHelper(s, counter);
                    counter.increment();    // skip ')'
                }
    
                if (counter.get() < s.length() && s.charAt(counter.get()) == '(') {
                    counter.increment();    // skip '('
                    current.right = str2treeHelper(s, counter);
                    counter.increment();    // skip ')'
                }
    
                return current;
            }
        }
    
        private int parseInt(final String s, final Counter counter) {
            int start = counter.get();
            int i = s.charAt(start) == '-' ? start+1 : start;
            while (i < s.length() && Character.isDigit(s.charAt(i))) {
                i++;
            }
    
            String digits = s.substring(start, i);
            counter.increment(digits.length());
            return Integer.parseInt(digits);
        }
    }
    

Log in to reply
 

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