436. 寻找右区间【中等题】【每日一题】
思路:【TreeMap】
无情的API调用机器。
代码:
class Solution {
public int[] findRightInterval(int[][] intervals) {
int n = intervals.length;
int[] ans = new int[n];
if (n == 1){
ans[0] = -1;
return ans;
}
//建立一个treeMap用来存储每个区间的左端点及其对应在区间数组中的下标
TreeMap left = new TreeMap<>();
for (int i = 0; i < n; i++) {
left.put(intervals[i][0],i);
}
//遍历区间,调用treeMap的ceilingEntry函数求大于等于当前区间右端点的最小左端点
for (int i = 0; i < n; i++) {
Map.Entry ceilingEntry = left.ceilingEntry(intervals[i][1]);
//如果存在大于等于当前区间右端点的最小左端点,则将ans[i]设为这个最小左端点对应在区间数组中的下标
//如果不存在这样的最小左端点,则将ans[i]置为 -1
ans[i] = ceilingEntry == null ? -1 : ceilingEntry.getValue();
}
return ans;
}
}
剑指 Offer II 052. 展平二叉搜索树【简单题】
思路:
中序遍历给定二叉搜索树,将遍历到的每个节点依次放到ans根节点的右侧节点位置。
代码1:
class Solution {
public TreeNode increasingBST(TreeNode root) {
List list = new ArrayList<>();
dfs(root,list);
TreeNode ans = new TreeNode();
TreeNode node = ans;
for (Integer integer : list) {
node.right = new TreeNode(integer);
node = node.right;
}
return ans.right;
}
public void dfs(TreeNode root,List list){
if (root == null){
return;
}
dfs(root.left,list);
list.add(root.val);
dfs(root.right,list);
}
}
代码2:
class Solution {
TreeNode ans = new TreeNode();
TreeNode node = ans;
public TreeNode increasingBST(TreeNode root) {
dfs(root);
return ans.right;
}
public void dfs(TreeNode root){
if (root == null){
return;
}
dfs(root.left);
node.right = new TreeNode(root.val);
node = node.right;
dfs(root.right);
}
}
剑指 Offer II 053. 二叉搜索树中的中序后继【中等题】
思路:
题目要求的中继节点,就是将二叉搜索树中序遍历之后 p节点右侧的那个节点。
根据二叉搜索树的性质,如果p节点有右子树,那么中继节点target就是p节点的右子树中最靠左的那个节点;如果p节点没有右子树,那么中继节点target存在于p节点的上方,此时需要从根节点root开始遍历二叉搜索树,设遍历到的节点为node,那么当node的值大于p时,说明此时node可能是中继节点,我们需要缩小node的范围,从node的左子节点开始继续遍历,确保它就是中继节点;当node的值小于p时,说明此时node不可能是中继节点,因此我们直接舍掉node的左子树,从node的右子节点开始继续遍历。
代码:
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
//定义目标节点 target就是我们要找的 p节点的中序后继节点
TreeNode target = null;
//如果p的右子树不为空,那么p的中序后继一定在其右子树中
if (p.right != null){
//将target更新为p的右子树根节点
target = p.right;
//根据二叉搜索树的性质,将target更新为 右子树中 值最小的节点
while (target.left != null){
target = target.left;
}
return target;
}
//如果p的右子树为空,那么需要从根节点开始遍历寻找p节点的祖先节点
TreeNode node = root;
while (node != null){
//当前节点的值大于 p节点的值 说明 node在p的后边,有可能是中继节点,将target更新为node,并将node更新为node.left,缩小范围继续判断以求找到大于p.val的最小节点,即p的中继节点
if (node.val > p.val){
target = node;
node = node.left;
}else {//如果当前节点的值小于p节点的值 说明当前node在p的前边,不可能是中继节点,需要扩大筛选范围 将 node 更新为 node.right
node = node.right;
}
}
return target;
}
}



