构建二叉树 mirror中序遍历 A了
static String solution(String input) {
TreeNode node = solutionSub(input);
String result = treeMid(node);
return result;
}
public static String treeMid(TreeNode head) {
StringBuilder sb = new StringBuilder();
if (head == null) return null;
TreeNode cur1 = head;
TreeNode cur2 = null;
while (cur1 != null) {
cur2 = cur1.left;
if (cur2 != null) {
while (cur2.right != cur1 && cur2.right != null) {
cur2 = cur2.right;
}
if (cur2.right != cur1) {
cur2.right = cur1;
cur1 = cur1.left;
continue;
} else {
cur2.right = null;
}
}
sb.append(cur1.val);
cur1 = cur1.right;
}
return sb.toString();
}
static TreeNode solutionSub(String input) {
if (input == null || input.length() == 0) return null;
Integer i = Integer.valueOf(input.substring(0, 1));
TreeNode node = new TreeNode(i);
if (input.length() > 1) {
String child = input.substring(2, input.length() - 1);
int left = 0;
int right = 0;
int mid = 0;
for (int j = 0; j < child.length(); j++) {
if (child.charAt(j) == '(') {
left++;
continue;
}
if (child.charAt(j) == ')') {
right++;
continue;
}
if (child.charAt(j) == ',' && left == right) {
mid = j;
break;
}
}
String leftChild = child.substring(0, mid);
String rightChild = child.substring(mid + 1);
TreeNode le = solutionSub(leftChild);
TreeNode ri = solutionSub(rightChild);
node.left = le;
node.right = ri;
}
return node;
}