1. 程式人生 > 實用技巧 >[LeetCode] 510. Inorder Successor in BST II

[LeetCode] 510. Inorder Successor in BST II

Given anodein a binary search tree, findthe in-order successor of that node in the BST.

If that node has no in-order successor, returnnull.

The successor of anodeis the node with the smallest key greater thannode.val.

You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node.Below is the definition forNode

:

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node parent;
}

Follow up:

Could you solveit withoutlooking up any of thenode's values?

Example 1:

Input: tree = [2,1,3], node = 1
Output: 2
Explanation: 1's in-order successor node is 2. Note that both the node and the return 
value is of Node type.

Example 2:

Input: tree = [5,3,6,2,4,null,null,1], node = 6
Output: null
Explanation: There is no in-order successor of the current node, so the answer is null.

Example 3:

Input: tree = [15,6,18,3,7,17,20,2,4,null,13,null,null,null,null,null,null,null,null,9], 
node = 15 Output: 17

Example 4:

Input: tree = [15,6,18,3,7,17,20,2,4,null,13,null,null,null,null,null,null,null,null,9], 
node = 13 Output: 15

Example 5:

Input: tree = [0], node = 0
Output: null

Constraints:

  • -10^5 <= Node.val <= 10^5
  • 1 <= Number of Nodes <=10^4
  • All Nodes will have unique values.

二叉搜尋樹中的中序後繼 II。這道題是285題的延續,但是題設稍微有些變化。這道題給的是一個隨機的節點node,不給你根節點了;給你這個節點node的同時,可以允許你訪問這個節點的val,左孩子,右孩子和父親節點。依然是請你返回這個節點的中序後繼。

思路分兩部分,如果這個節點自己有右子樹怎麼辦,和如果這個節點沒有右子樹怎麼辦。第一種情況,如果有右子樹,那麼直截了當,要找的節點就是node.right。第二種情況,如果沒有右子樹,那麼要找的中序後繼分兩種情況,一種是如果我是一個左子樹,我要找的很顯然是我的最直接的父親節點,比如例子4裡面的2,我找的應該是3,3就是2的父親節點。

還有一種情況是比如我是4(例子2),我是左子樹的最右孩子,我的中序遍歷的後繼節點是根節點5,我不光要試圖往父親節點跑,同時我還需要判斷,我每往上走一步的時候,我到達的這個節點的右孩子到底是不是我自己,否則就會報錯。

時間O(n)

空間O(1)

Java實現

 1 class Solution {
 2     public Node inorderSuccessor(Node node) {
 3         // corner case
 4         if (node == null) {
 5             return null;
 6         }
 7         // if right tree is not empty
 8         // find the most left node on this right tree
 9         if (node.right != null) {
10             Node suc = node.right;
11             while (suc.left != null) {
12                 suc = suc.left;
13             }
14             return suc;
15         }
16 
17         // if right tree is empty
18         while (node.parent != null && node.parent.right == node) {
19             node = node.parent;
20         }
21         return node.parent;
22     }
23 }

相關題目

285. Inorder Successor in BST

510. Inorder Successor in BST II

LeetCode 題目總結