简体   繁体   中英

Inorder successor in a binary search tree

This is a common algorithm question. I'm trying to find the inorder successor in a binary search tree. Here's my code

def inorderSuccessor(self, root, p):
        """
        :type root: TreeNode
        :type p: TreeNode
        :rtype: TreeNode
        """
        # if Node has a right child, go all the way down
        if p.right:
            curr = p
            while curr.left:
                curr = curr.left
            return curr
        # first ancestor whose left child the node is
        ans = None
        curr = root
        while curr is not p:
            if curr.val < p.val:
                curr = curr.right
            else:
                ans = curr
                curr = curr.left
        return ans

The problem is that this doesn't work when p is the highest node in the tree. I've been scratching my head over how to get this edge case going.

You can implement a method within your BST Class as below

def InOrderSucc(self,childNode):
    if(self.search(childNode)):
        if not (self.data == childNode):
            return(self.right.InOrderSucc(childNode))
        else:
            if(self.right):
                return(self.right.data)
            else:
                return None
    else:
        return False

where childNode is the Node you are requesting to find its InOrder Successor, Noting that the InOrder Successor will always be the right Child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM