数组变MaxTree-java
public int[] buildMaxTree(int[] A, int n) { // write code here if (A == null || n < 1) { return null; } Stack<Integer> findStack = new Stack<Integer>(); Integer[] leftMax = new Integer[n]; Integer[] rightMax = new Integer[n]; for (int i = 0; i < n; i++) { while (!findStack.empty() && A[findStack.peek()] <= A[i]) { findStack.pop(); } if (findStack.empty()) leftMax[i] = null; else leftMax[i] = findStack.peek(); findStack.push(new Integer(i)); } while (!findStack.empty()) { findStack.pop(); } for (int i = n - 1; i >= 0; i--) { while (!findStack.empty() && A[findStack.peek()] <= A[i]) { findStack.pop(); } if (findStack.empty()) rightMax[i] = null; else rightMax[i] = findStack.peek(); findStack.push(new Integer(i)); } int[] res = new int[n]; int j = 0; for (int i = 0; i < n; ++i) { if (leftMax[i] != null && rightMax[i] != null) { if (A[leftMax[i]] < A[rightMax[i]]) res[j++] = leftMax[i]; else res[j++] = rightMax[i]; } else if (leftMax[i] != null && rightMax[i] == null) { res[j++] = leftMax[i]; } else if (leftMax[i] == null && rightMax[i] != null) { res[j++] = rightMax[i]; } else { res[j++] = -1; } } return res; }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 数组变树练习
- 下一篇: 【难】【二叉树】构造数组的MaxTree