Concise Java


  • 0
    class Solution {
        public TreeNode str2tree(String s) {
            if (s == null || s.length() == 0) return null;
            Stack<TreeNode> stack = new Stack<>();
            int i = 0;
            int val = helper(s, i, 0, 1);
            stack.push(new TreeNode(val));
            while (i < s.length()) {
                char c = s.charAt(i++);
                if (c == '(') {
                    val = helper(s, i, 0, 1);
                    TreeNode node = new TreeNode(val);
                    if (stack.peek().left == null) stack.peek().left = node;
                    else stack.peek().right = node;
                    stack.push(node);
                } else if (c == ')') {
                    stack.pop();
                }
            }
            return stack.peek();
        }
        private int helper(String s, int i, int num, int op) {
            if (s.charAt(i) == '-') {
                op = -1;
                i++;
            }
            while (i < s.length() && Character.isDigit(s.charAt(i))) {
                num = num * 10 + s.charAt(i) - '0';
                i++;
            }
            return num * op;
        }
    }
    

Log in to reply
 

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