zoukankan      html  css  js  c++  java
  • leetcode-mid-Linked list- 230 Kth Smallest Element in a BST

    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()
  • 相关阅读:
    辞职后的第二个星期
    最近似乎应该休眠了.
    文件.二进制转换
    AVL树
    ajax 的同步和异步
    在SQL Server实现最短路径的搜索
    网页嵌套com例子
    Vs2005 dll 设置def导出函数
    [转]ATL开发一个ActiveX
    Atl COM发布与优化
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10968964.html
Copyright © 2011-2022 走看看