題目地址:
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;
}
}
時間複雜度,空間。