Easy to Understand but not Optimal


  • 0
    S
    public class Solution {
        public TreeNode str2tree(String s) {
            Stack<TreeNode> nodes = new Stack<TreeNode>();
            Stack<Character> symbols = new Stack<Character>();
            if(s.length()==0) return null;
            int sign=1;
            int num=0;
            char prev=' ';
            for(int i=0;i<s.length();i++){
                char c= s.charAt(i);
                if(c=='-'){
                    sign=-1;
                }
                else
                if(Character.isDigit(c)){
                    num = num * 10 + (Character.getNumericValue(c));
                }
                else
                if(c=='('){
                    symbols.push(c);
                    if(Character.isDigit(prev)){
                        nodes.push(new TreeNode(sign*num));
                        sign=1;
                        num=0;
                    }
                        
                }
                else
                if(c==')'){
                    if(Character.isDigit(prev)){
                        nodes.push(new TreeNode(sign*num));
                        sign=1;
                        num=0;
                    }
                    
                    
                    TreeNode child = nodes.pop();
                    TreeNode parent =nodes.pop();
                    if(parent.left==null){
                        parent.left=child;
                    }else{
                        parent.right=child;
                    }
                    nodes.push(parent);
                    
                    symbols.pop();
                }
                
                prev=c;
            }
            if(num!=0){
                nodes.push(new TreeNode(sign*num));
            }
            return nodes.pop();
        }
    }
    

Log in to reply
 

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