思路
- 思路1: 直接递归寻找后继,不考虑BST的性质,当作一般的二叉树来考虑。用递归很容易实现。
时间复杂度O(n),空间复杂度O(log n)(递归栈) - 思路2:考虑BST的性质,类似二分的思想(为了O(h)的复杂度)。每次将p与root的值进行对比:(1)p>=root, 则搜索右子树;
(2)p<root, 则搜索左子树,后继存在两种可能性:root或者左子树中的某个节点。如果在左子树中没搜到(null),则说明为root;否则为搜到的结果。【可以拿一棵3个节点的树来思考,always思考最简单的情况来递归给出定义】
时间复杂度O(h)=O(logn), 空间复杂度O(h)
代码
- 思路1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
/*
* @param root: The root of the BST.
* @param p: You need find the successor node of p.
* @return: Successor of p.
*/
TreeNode prev = null, res = null;
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
// write your code here
// prev = root;
inorder(root, p);
return res;
}
public void inorder(TreeNode root, TreeNode p) {
if(root == null) return;
inorder(root.left, p);
if(prev == p) {
res = root;
}
prev = root;
inorder(root.right, p);
}
}
- 思路2
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
/*
* @param root: The root of the BST.
* @param p: You need find the successor node of p.
* @return: Successor of p.
*/
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
// write your code here
if(root == null || p == null)
return null;
if(root.val <= p.val) {
return inorderSuccessor(root.right, p);
} else {
TreeNode leftRes = inorderSuccessor(root.left, p);
return (leftRes == null) ? root : leftRes;
}
}
}