• 剑指 Offer 54. 二叉搜索树的第k大节点





    方法一:BFS模板的应用。

    总结的DFS、BFS模板参考:https://www.cnblogs.com/panweiwei/p/13065661.html

    class Solution(object):
        # BFS
        def kthLargest(self, root, k):
            """
            :type root: TreeNode
            :type k: int
            :rtype: int
            """
            if not root:
                return
            res = []
            stack = [root]
            while stack:
                sizestack = len(stack)
                for i in range(sizestack):
                    node = stack.pop(0)
                    res.append(node.val)
                    if node.left:
                        stack.append(node.left)
                    if node.right:
                        stack.append(node.right)
            # 要返回的是第k大,所以降序排;若是第k小,则升序排
            res.sort(reverse=True)
            return res[k - 1]
    
    

    方法二:DFS,二叉搜索树的中序遍历就是有序序列。

    class Solution(object):
        # DFS:二叉搜索树的中序遍历就是有序序列。
        def kthLargest(self, root, k):
            """
            :type root: TreeNode
            :type k: int
            :rtype: int
            """
            if not root:
                return
            res = self.mid_DFS(root)
            return res[len(res) - k]
    
        def mid_DFS(self, root):
            # 特判:树根为空
            if not root:
                return []
            # 返回值
            res = []
            res += self.mid_DFS(root.left)
            res.append(root.val)
            res += self.mid_DFS(root.right)
            return res
    
  • 相关阅读:
    生成器
    迭代器
    闭包函数
    装饰器(2)
    装饰器(1)
    名称空间与作用域(2)
    110.网络编程-mail
    109.网络编程-FTP
    108.网络编程-TCP/UDP
    107.xpath
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13661834.html
Copyright © 2020-2023  润新知