Python easiest to understand recursive solution!


  • 0
    A
    class Solution(object):
        def countnodes(self, root):
            if not root:
                return 0
            l=self.countnodes(root.left)
            r=self.countnodes(root.right)
            return 1+l+r
            
        def kthSmallest(self, root, k):
            return self.getkth(root,k)
            
        def getkth(self, root, k):
            cc=self.countnodes(root.left)
            if 1+cc==k:
                return root.val
            elif 1+cc>k:
                return self.getkth(root.left, k)
            else:
                return self.getkth(root.right, k-1-cc)
    

Log in to reply
 

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