链接:https://www.nowcoder.com/questionTerminal/a502c7c3c65e41fdaf65eec9e0654dcb
来源:牛客网
对于一个没有重复元素的整数数组,请用其中元素构造一棵MaxTree,MaxTree定义为一棵二叉树,其中的节点与数组元素一一对应,同时对于MaxTree的每棵子树,它的根的元素值为子树的最大值。现有一建树方法,对于数组中的每个元素,其在树中的父亲为数组中它左边比它大的第一个数和右边比它大的第一个数中更小的一个。若两边都不存在比它大的数,那么它就是树根。请证明这个方法的正确性,同时设计O(n)的算法实现这个方法。
给定一个无重复元素的数组A和它的大小n,请返回一个数组,其中每个元素为原数组中对应位置元素在树中的父亲节点的编号,若为根则值为-1。
import java.util.*;
public class MaxTree {
public int[] buildMaxTree(int[] A, int n) {
// write code here
if (A == null || A.length == 0 || n <= 0) {
return new int[0];
}
Stack<Integer> stack = new Stack<>();
int[] res = new int[n];
for (int i = 0; i < n; ++ i) {
res[i] = -1;
}
/**
* 正序遍历,寻找右侧第一个
*/
for (int i = 0; i < n; ++ i) {
while (! stack.isEmpty() && A[stack.peek()] < A[i]) {
res[stack.pop()] = i;
}
stack.push(i);
}
/**
* 逆序遍历,寻找左侧第一个
*/
for (int i = n - 1; i >= 0; -- i) {
while (! stack.isEmpty() && A[stack.peek()] < A[i]) {
int top = stack.pop();
if (res[top] == -1) {
res[top] = i;
} else if (A[res[top]] > A[i]) {
res[top] = i;
}
}
stack.push(i);
}
return res;
}
}