My solution, using stack:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    int i=0;
    public TreeNode str2tree(String s) {
        if(s==null || s.length()==0)
            return null;
        Stack<TreeNode> stk = new Stack<>();
        int j=0;
        while(i<s.length()){
            j=i;
            char c = s.charAt(i);
            if(c == ')'){ 
                stk.pop();
                i++;
            }
            else if(c=='('){
                i++;
            }
            else {
                int val = getVal(s);
                TreeNode currentNode = new TreeNode(val);
                if(!stk.isEmpty()){
                    TreeNode parent = stk.peek();
                    if(parent.left != null)    
                        parent.right = currentNode;
                    else parent.left = currentNode;
                }
                stk.push(currentNode);
            }
        }
        return stk.pop();
    }
    
    private int getVal(String s){
        StringBuilder sb = new StringBuilder();
        while(i<s.length()&&(Character.isDigit(s.charAt(i))||s.charAt(i)=='-')){
            sb.append(s.charAt(i++));
        }
        return Integer.valueOf(sb.toString());
    }
}

 

posted on 2022-04-12 12:34  阳光明媚的菲越  阅读(15)  评论(0编辑  收藏  举报