GuilinDev

Lc0510

05 August 2008

510. Inorder Successor in BST II

跟285比,这个题只给node,不给root

If the node has right node, find the left most node from its right node. Else get parent that is just greater than given node.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public Node inorderSuccessor(Node node) {
        if(node.right!=null) return getLeftMost(node.right);
        else return getParentJustGT(node);
    }
    
    public Node getLeftMost(Node node){
        return node.left!=null? getLeftMost(node.left):node;
    }
    
    //Get Parent node just greater than the given node.
    public Node getParentJustGT(Node node){
        Node par = node.parent;
        while(par!=null && par.val<node.val) par = par.parent;
        return par;
    }
}