Share my Java recursive solution


  • 0
    S
    public class Solution {
        public TreeNode str2tree(String s) {
            if (s.length() == 0) return null;
            char[] tokens = s.toCharArray();
            int n = tokens.length;
            int start = -1;
            int mid = -1;
            int count = 0;
            for (int i = 0; i < n; i++) {
                if (tokens[i] == '(') {
                    if (start == -1) start = i;
                    count++;
                }
                else if (tokens[i] == ')') {
                    count--;
                    if (count == 0) {
                        mid = i;
                        break;
                    }
                }
            }
            if (start == -1) return new TreeNode(Integer.parseInt(s));
            TreeNode root = new TreeNode(Integer.parseInt(s.substring(0, start)));
            root.left = str2tree(s.substring(start + 1, mid));
            if (mid + 2 < s.length() - 1) root.right = str2tree(s.substring(mid + 2, s.length() - 1));
            return root;
        }
    }
    

Log in to reply
 

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