1. 二叉搜索树中的中序后继
三种情况:
(1)root的值大于p
- 比如[2,1,3],p=1,root=2时,我们可以确定p一定在左子树上
- 进一步地,如果左子树上有它的中序后继,那就直接返回即可。
- 如果左子树没有它的中序后继,那当前这个root(2)就是比它大的值,所以返回root即可
(2)root的值等于p
- 这种情况下,中序后继要么是在root/p的右子树上,要么就是当前root/p的父节点
- 所以先到右子树上找inorderSuccessor(root.right,p);找得到直接返回,找不到返回null
- 父节点拿到结果一看,这个p在左子树
- 但是中序后继是null,只好把自己(这个父节点自己)返回了
- 真有中序后继,那就直接返回吧
(3)root的值小于p
- p肯定在右子树上,它的中序后继肯定在右子树上,所以直接返回inorderSuccessor(root.right,p)即可
- 有就有,没有就没有了
(1)递归
递归执行中序遍历,在递归过程中获取x的下一个。如果当前值是<=x的,那么根据BST的特性只需要在右子树中找。如果当前值 > x,则当前值有可能,它的左子树也有可能有更小的但是也 > x的,对左子递归后,选择更接近的(更小的).
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (p == null || root == null) {
return null;
}
//当前和左边都不可能 > p
if (root.val <= p.val) {
return inorderSuccessor(root.right,p);
}
//root > p
TreeNode res = inorderSuccessor(root.left, p);
if (res != null && res.val < root.val) {
return res;
} else {
return root;
}
}
}
(2)中序+ 二分
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
List<TreeNode> list = new ArrayList<>();
inOrder(root, list); //中序遍历后,所有节点都升序 放入list中
//二分查找
int left = 0, right = list.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (list.get(mid).val == p.val) {
if (mid + 1 < list.size()) {
return list.get(mid + 1);
}else {
return null;
}
} else if (list.get(mid).val > p.val) {
right = mid;
} else {
left = left + 1;
}
}
return null;
}
public static void inOrder(TreeNode root, List<TreeNode> list) {
if (root == null) {
return;
}
inOrder(root.left, list);
list.add(root);
inOrder(root.right, list);
}
}
(3)BFS
- 如果当前值是<=x的,那么根据BST的特性只需要在右子树中找:cur=cur.right。
- 如果当前值>x,则当前值有可能,它的左子树也有可能有更小的但是也>x的。则每次走入这个分支时,当前点是一个候选点,记录该节点的值和历史最小节点的值。
- 时间O(logN),空间O(1)
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (p == null || root == null){
return null;
}
TreeNode cur=root;
TreeNode res=null;
while (cur != null) {
if (cur.val <= p.val) {
cur=cur.right;
} else {
if (res == null || res.val > cur.val) {
res = cur;
}
cur = cur.left;
}
}
return res;
}
}