mycode  81.40%

# 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
        """
        self.res = []
        def inorder(root):
            if not root:
                return 
            inorder(root.left)
            self.res.append(root.val)
            inorder(root.right)
        inorder(root)
        return self.res[k-1]

 

参考

思路:

我的方法中先将整个tree都遍历了一遍,其实是不必要的,那么该如何恰好在找到第k个数的时候及时退出呢-》

def kthSmallest(root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        s = []
        p = root
        cnt = 0
        print('p',p)
        while s or p:
            if p:
                s.append(p)
                print('if',p.val,s)
                p = p.left     
            else:
                p = s[-1].right
                cnt += 1  #上面之所以能取出p是因为已经没有左子树了,所以最后左子树的叶子就是目前数里面最小的数,计数+1
                print('else',s)
                if cnt == k:
                    return s[-1].val
                s.pop()