285. Inorder Successor in BST

https://leetcode.com/problems/inorder-successor-in-bst/#/description 

Given a binary search tree and a node in it, find the in-order successor of that node in the BST.

Note: If the given node has no in-order successor in the tree, return null.

Back-up knowledge. 

1  Inorder by definition:

We recursively do an inorder traversal on the left subtree, visit the root node, and finally do a recursive inorder traversal of the right subtree. 

(So, you can see by definition, we have to call this function recursively on both sides of tree . )

2 Inorder codes:

def inorder(tree):

    if tree != None:

        inorder(tree.getLeftChild())

        print (tree.getRootVal())

        inorder(tree.getRightChild())

Sol 1:

Recursion.

If node p on the right subtree, then call the function recursively on the right subtree.

Otherwise, node p is on the left subtree, then  call the function recursively on the left subtree or the root. 

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def inorderSuccessor(self, root, p):
        """
        :type root: TreeNode
        :type p: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        if root.val <= p.val:
            return self.inorderSuccessor(root.right, p)
        return self.inorderSuccessor(root.left, p) or root

Note:

1 GIven BST, we must use the attribute of BTS:

roo.left.val < root.val < root.right.val

Otherwise, you cannot crack the BST problem....

Plus, for BST, "isRightChild" function equals to "if p.val > root.val"

Sol 2:

 "succ" here is to track  all possible successors

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def inorderSuccessor(self, root, p):
        """
        :type root: TreeNode
        :type p: TreeNode
        :rtype: TreeNode
        """
        # iterative 
        # The inorder traversal of a BST is the nodes in ascending order. To find a successor, you just need to find the smallest one that is larger than the given value since there are no duplicate values in a BST. It just like the binary search in a sorted list. The time complexity should be O(h) where h is the depth of the result node. succ is a pointer that keeps the possible successor. Whenever you go left the current root is the new possible successor, otherwise the it remains the same.

        # Only in a balanced BST O(h) = O(log n). In the worst case h can be as large as n.
        
        
        succ = None
        while root:
            if p.val < root.val:
                succ = root
                root = root.left
            else:
                root = root.right
        return succ
原文地址:https://www.cnblogs.com/prmlab/p/7126341.html