100% Python 3 solution using pre-order search


  • 0
    A
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def kthSmallest(self, root, k):
            """
            :type root: TreeNode
            :type k: int
            :rtype: int
            """
            # find the smallest one
            smallest = root
            parents = []
            while smallest.left:
                parents.append(smallest)
                smallest = smallest.left
            # keep getting next one to find k smallest number
            node = smallest
            while k > 1:
                # get next
                if node.right:
                    parents.append(node)
                    node = node.right
                    while node.left:
                        parents.append(node)
                        node = node.left
                else:
                    p = parents.pop()
                    while p.left != node:
                        node = p
                        p = parents.pop()
                    node = p
                k -= 1
            return node.val
        ```

Log in to reply
 

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