Python - Inorder solution


  • 0
    A
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def kthSmallest(self, root, k):
            """
            :type root: TreeNode
            :type k: int
            :rtype: int
            """
            stack = []
            done = False
            stack.append(root)
            curr = root
            while not done:
                if curr:
                    stack.append(curr)
                    curr = curr.left
                else:
                    if stack:
                        curr = stack.pop()
                        if k == 1:
                            return curr.val
                        k-=1
                        curr = curr.right
                    else:
                        done = True
                    
    

Log in to reply
 

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