smj007

Untitled

Jun 20th, 2022
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | None | 0 0
  1. # # Implementation 1:
  2. # # Build an array of elements and then access the kth element
  3.  
  4. class Solution:
  5.     def kthSmallest(self, root, k):
  6.         """
  7.        :type root: TreeNode
  8.        :type k: int
  9.        :rtype: int
  10.        """
  11.         def inorder(r):
  12.             return inorder(r.left) + [r.val] + inorder(r.right) if r else []
  13.    
  14.         return inorder(root)[k - 1]
  15.  
  16.  
  17. # Implementation 2:
  18. # Do an inorder transversal and increment the global counter by 1 every time you encounter the
  19. # root node. Check if count till now == the number that you are looking for
  20. # as soon as you found
  21.  
  22. class Solution:
  23.     def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
  24.        
  25.         self.count = 0
  26.         self.result = None
  27.         self.k = k
  28.    
  29.         self.transverse(root)
  30.        
  31.         return self.result
  32.        
  33.     def transverse(self, root: Optional[TreeNode]) -> int:
  34.        
  35.         if not root:
  36.             return
  37.        
  38.         # suppress future call stacks
  39.         if self.result:
  40.             return
  41.        
  42.         if not self.result:
  43.             self.transverse(root.left)
  44.    
  45.         # suppress future call stacks
  46.         if not self.result:
  47.             self.count += 1
  48.             if self.count == self.k:
  49.                 self.result = root.val
  50.                 return
  51.            
  52.         # suppress future call stacks
  53.         if not self.result:        
  54.             self.transverse(root.right)
Advertisement
Add Comment
Please, Sign In to add comment