题目地址:
https://www.lintcode.com/problem/inorder-successor-in-bst/description
给定一棵BST,再给定树中的一个节点,求中序遍历中的后继节点。
中序遍历的后继节点,等价于整棵树中比大的所有节点中最小的数。这道题和以下这题Inorder Predecessor in BST很像,参考:https://blog.csdn.net/qq_46105170/article/details/105885857。思路是新开一个指针跟在root后面,然后根据和的关系决定向哪个方向走。如果小于等于,那么整棵左子树都比更小,所以不可能在左子树里,向右走一步;如果大于,那么就新开一个指针跟在后面,然后将向左走。如果本身就是最大值,那么最终会一路向右走到null,此时维持默认值null,所以可以返回;如果无右子树,那么会拐到右边成为,此时是的右父亲,也是返回;如果有右子树,那么会拐到的右子树,然后跟在后面一路向左走,走到最后一个节点的时候就可以返回(此时成为null)。代码如下:
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
TreeNode succ = null;
while (root != null) {
if (root.val <= p.val) {
root = root.right;
} else {
// 此时root.val > p.val
succ = root;
root = root.left;
}
}
return succ;
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
时间复杂度,空间。