/**
* 审题:(这个题真的看了好多遍才明白)
* 一共三个数组,最后一个数组是指定的结点,前两个数组一个表示左子树,一个表示右子树,怎么看呢?(重点!)
* 根结点的值是1,所以,要找左子树,[1-1]得到下标0,
* 在左子树的数组找1的左儿子,如示例1,对应的左儿子是4,
* 在右子树的数组找1的右儿子,如示例1,对应的右儿子是2,
* 如果左儿子的值不为0,[左儿子-1]得到下标,
* 如示例1,得到下标3,找到4的右儿子是5,左子树数组对应的值是0,所以没有左儿子
* 如果右儿子的值不为0,[右儿子-1]得到下标,
* 如示例1,得到下标1,找到2的左儿子是3,没有右儿子
* 继续寻找...
* 如示例1,得到二叉树
* 1
* 4 2
* 5 3
* 大体思路:读题,需要两个功能:旋转,中序遍历
* 中序遍历时,需要额外注意一点,要定义一个静态变量用来控制存储数组的下标,
* 如果想要将值带在参数传过去,会出现错误,因为左子树和右子树参数不通
* 旋转时一定要注意if的使用,否则会出现数组下标越界错误
*/
public static int cur = 0;
public int[] solve(int n, int m, int[] l, int[] r, int[] k) {
for (int i : k) {
treeSwap(l, r, i - 1);
}
int[] result = new int[n];
inOrder(result, l, r, 1);
return result;
}
// 旋转
public void treeSwap(int[] l, int[] r,int index) {
if (l[index] == 0&& r[index] == 0) {
return;
}
int temp = l[index];
l[index] = r[index];
r[index] = temp;
if (l[index] != 0) {
treeSwap(l, r, l[index] - 1);
}
if (r[index] != 0) {
treeSwap(l, r, r[index] - 1);
}
}
// 中序遍历
public void inOrder(int[] result, int[] l, int[] r, int temp) {
if (l[temp - 1] != 0) {
inOrder(result, l, r, l[temp - 1]);
}
result[cur++] = temp;
if (r[temp - 1] != 0) {
inOrder(result, l, r, r[temp - 1]);
}
}