题目地址:
https://leetcode.com/problems/depth-of-bst-given-insertion-order/
给定一个长 n n n数组 A A A,按次序将这些数插入一个二叉搜索树,该树节点不会发生旋转。问插入完成之后树的深度。树的深度定义为从树根出发的最长链的节点个数。
如果树空,那么插入的节点的深度显然是 1 1 1。用一个TreeMap存一下每个节点的深度。考虑在插入某个节点 x x x的时候, x x x会插在什么地方。如果树中没有比 x x x更大的节点了,那么就找到小于等于 x x x的最大节点, x x x会插在它的下面;同样,如果树中没有比 x x x更小的节点了,那么就找到大于等于 x x x的最小节点, x x x会插在它的下面;如果 x x x同时有小于等于它的最大数和大于等于它的最小数,那么在插入 x x x的时候,一定会先经过两者更浅的那个,然后走到两者更深的那个,然后接在下面(这可以用数学归纳法证明)。代码如下:
import java.util.Map;
import java.util.TreeMap;
public class Solution {
public int maxDepthBST(int[] order) {
TreeMap<Integer, Integer> map = new TreeMap<>();
int res = 0;
for (int x : order) {
if (map.isEmpty()) {
map.put(x, 0);
} else {
Map.Entry<Integer, Integer> floor = map.floorEntry(x), ceil = map.ceilingEntry(x);
int depth = 0;
if (floor != null) {
depth = Math.max(depth, floor.getValue());
}
if (ceil != null) {
depth = Math.max(depth, ceil.getValue());
}
map.put(x, depth + 1);
}
res = Math.max(res, map.get(x));
}
return res;
}
}
时间复杂度 O ( n log n ) O(n\log n) O(nlogn),空间 O ( n ) O(n) O(n)。