5 line Python recursive solution (beats 96%)


  • 0
    P
    class Solution(object):
        
        def kthSmallest(self, root, k):
            """
            :type root: TreeNode
            :type k: int
            :rtype: int
            """
            self.k = k
            self.solution = []
            self.perform_in_order_traverse(root)
    
            return self.solution[k-1]
            
    
        def perform_in_order_traverse(self, root_node):
            if root_node != None and len(self.solution) < self.k:
                self.perform_in_order_traverse(root_node.left)
                self.solution += [root_node.val]
                self.perform_in_order_traverse(root_node.right)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.