Java Solution 14ms no need to account for parenthesis


  • 0
    R
    class Solution {
        int pos = 0;
        
        public TreeNode str2tree(String s) {
            if (pos >= s.length()) return null;
            if (s.charAt(pos) == ')') {
                ++pos;
                return null;
            }
            int val = parseInt(s);
            TreeNode node = new TreeNode(val);
            if (pos < s.length() && s.charAt(pos) == ')') {
                return node;
            } else {
                ++pos;
                node.left = str2tree(s);
                ++pos;
            }
            if (pos < s.length() && s.charAt(pos) == ')') {
            } else {
                ++pos;
                node.right = str2tree(s);
                ++pos;
            }
    
            return node;
        }
    
        
        int parseInt(String s) {
            int minus = 1;
            if (s.charAt(pos) == '-') {
                minus = -1; ++pos;
            }
            int num = 0;
            while (pos < s.length() && Character.isDigit(s.charAt(pos))) {
                num = num * 10 + (s.charAt(pos) - '0');
                ++pos;
            }
            return num * minus;
        }
    }
    

Log in to reply
 

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