zoukankan      html  css  js  c++  java
  • 剑指 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
    
  • 相关阅读:
    css基础属性
    选择器的类型
    css的三种表现形式
    表单和表格
    如何比较两个xml 的异同
    xslt 简单的语法
    xslt 和一个demo
    event based xml parser (SAX) demo
    SAX vs. DOM (Event vs. Tree)
    xmlns 实例分析
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13661834.html
Copyright © 2011-2022 走看看