Iam_Sandeep

Inorder successor predecessor in BST

Apr 20th, 2022
809
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. '''
  2. vvv imp
  3. while finding inorder predecessor if you are at target node then still you have to continue to left to check whether any element exists whose value is less than target and update it with predecessor
  4. '''
  5. class Solution:
  6.     """
  7.    @param root: the given BST
  8.    @param p: the given node
  9.    @return: the in-order predecessor of the given node in the BST
  10.    """
  11.     def inorderPredecessor(self, root, p):
  12.         cur=root
  13.         pre=None
  14.         while cur:
  15.             if p.val<=cur.val:
  16.                 cur=cur.left
  17.             else:
  18.                 pre=cur
  19.                 cur=cur.right
  20.         return pre
  21. '''
  22. while finding inorder successor if you are at target node then still you have to continue to left to check whether any element exists whose value is less than target and update it with successor
  23. '''
  24.  
  25. class Solution:
  26.     """
  27.    @param: root: The root of the BST.
  28.    @param: p: You need find the successor node of p.
  29.    @return: Successor of p.
  30.    """
  31.     def inorderSuccessor(self, root, p):
  32.         succ=None
  33.         cur=root
  34.         while cur:
  35.             if p.val<cur.val:
  36.                 succ=cur
  37.                 cur=cur.left
  38.             else:
  39.                 cur=cur.right
  40.         return succ
  41.  
Advertisement
Add Comment
Please, Sign In to add comment