Share my iterator solving code with explanation.


  • 0
    W
    //pop() when met ')' otherwise push(), that's it.
    public TreeNode str2tree(String s) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        for(int i = 0, j = i; i < s.length(); i++, j = i) {
            char ch = s.charAt(i);
            if(ch==')') stack.pop();
            else if(ch >= '0' && ch <= '9' || ch == '-'){
                while(i+1 < s.length() && s.charAt(i+1) >= '0' && s.charAt(i+1) <= '9') i++;
                TreeNode node = new TreeNode(Integer.parseInt(s.substring(j, i+1)));
                if(stack.isEmpty()) {
                    stack.push(node);
                } else {
                    TreeNode top = stack.peek();
                    if(top.left != null) top.right = node;
                    else top.left = node;
                    stack.push(node);
                }
            }
        }
        return stack.isEmpty() ? null : stack.pop();
    }

Log in to reply
 

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