My Java Solution using a Stack


  • 0
    F
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode str2tree(String str) {
            if(str==null || str.length()==0) {
                return null;
            } else {
                Stack<TreeNode> s = new Stack<>();
            
                str = new StringBuilder().append("(").append(str).toString();
                for(int idx = 0; idx < str.length(); ) {
                    if(str.charAt(idx)=='(') {
                        int end;
    
                        for(end = idx+1; end<str.length() && str.charAt(end)!='(' && str.charAt(end)!=')'; end++);
                        s.push(new TreeNode(Integer.parseInt(str.substring(idx+1, end))));
                        idx = end;
                    } else {
                        TreeNode child = s.pop(), parent = s.peek();
    
                        if(parent.left == null) {
                            parent.left = child;
                        } else {
                            parent.right = child;
                        }
                        idx++;
                    }
                }
    
                return s.pop();
            }
        }
    }
    

Log in to reply
 

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