536. Construct Binary Tree from String

You need to construct a binary tree from a string consisting of parenthesis and integers.

The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.

You always start to construct the left child node of the parent first if it exists.

 

Example 1:

Input: s = "4(2(3)(1))(6(5))"
Output: [4,2,6,3,1,5]

Example 2:

Input: s = "4(2(3)(1))(6(5)(7))"
Output: [4,2,6,3,1,5,7]

Example 3:

Input: s = "-4(2(3)(1))(6(5)(7))"
Output: [-4,2,6,3,1,5,7]

 1 class Solution {
 2     public TreeNode str2tree(String s) {
 3         return helper(s, 0, s.length() - 1);
 4     }
 5     private TreeNode helper(String s, int start, int end) {
 6         if (start > end) return null;
 7         int leftBraceIndex = s.indexOf('(', start);
 8         if (leftBraceIndex == -1 || leftBraceIndex > end) {
 9             String strValue = s.substring(start, end + 1);
10             return new TreeNode(Integer.valueOf(strValue));
11         }
12         int rootValue = Integer.valueOf(s.substring(start, leftBraceIndex));
13         TreeNode root = new TreeNode(rootValue);
14         int k = leftBraceIndex; 
15         int count = 0;
16         for (;k <= end; k++) {
17             if (s.charAt(k) == '(') {
18                 count++;
19             } else if (s.charAt(k) == ')') {
20                 count--;
21             }
22             
23             if (count == 0) {
24                 break;
25             }
26         }
27         root.left = helper(s, leftBraceIndex + 1, k - 1);
28         root.right = helper(s, k + 2, end - 1);
29         return root;
30     }
31 }

 

posted @ 2021-03-29 01:11  北叶青藤  阅读(24)  评论(0编辑  收藏  举报