LeetCode刷题实战536: 从字符串生成二叉树
ou 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.
示例
示例:
输入: "4(2(3)(1))(6(5))"
输出: 返回代表下列二叉树的根节点:
4
/ \
2 6
/ \ /
3 1 5
注意:
输入字符串中只包含 '(', ')', '-' 和 '0' ~ '9'
空树由 "" 而非"()"表示。
解题
class Solution {
public TreeNode str2tree(String s) {
if (s.length() == 0) return null;
StringBuilder value = new StringBuilder();
TreeNode root = new TreeNode();
int start = -1; // 第一个左括号的位置
// 确定根节点的权值
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
root.val = Integer.parseInt(value.toString());
start = i;
break;
}
if (i == s.length() - 1) {
value.append(s.charAt(i));
root.val = Integer.parseInt(value.toString());
return root;
}
value.append(s.charAt(i));
}
// 对左右子树递归求解
int count = 1; // 遇到左括号则++,遇到右括号则--
for (int i = start + 1; i < s.length(); i++) {
if ('(' == s.charAt(i)) count++;
if (')' == s.charAt(i)) count--;
if (count == 0) {
// 找到了左子树的区间
root.left = str2tree(s.substring(start + 1, i));
if (i != s.length() - 1) {
// 剩余的就是右子树的区间
root.right = str2tree(s.substring(i + 2, s.length() - 1));
}
break; // 左右子树整合完毕,结束
}
}
return root;
}
}