剑指offer - 题62,63(二叉搜索树,数据流中位数)

二叉搜索树的第k个结点
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回对应节点TreeNode
    def KthNode(self, pRoot, k):
        # write code here
        # 二叉搜索树(二叉排序树)的中序遍历结果已经是升序排序好的了,因为若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
        self.res=[]
        self.dfs(pRoot)
        return self.res[k-1] if len(self.res)>=k>0 else None
        
    def dfs(self,pRoot):
        if not pRoot:
            return
        self.dfs(pRoot.left)
        self.res.append(pRoot)
        self.dfs(pRoot.right)

数据流中的中位数
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。

# -*- coding:utf-8 -*-
# 熟悉heapq
from heapq import *
class Solution:
    def __init__(self):
        self.heaps=[], []
    def Insert(self, num):
        # write code here
        small,large=self.heaps
        # heappush(heap,item):往堆中插入一条新的值,heappop(heap):从堆中弹出最小值,heappushpop():将值插入到堆中同时弹出堆中的最小值。 
        heappush(small, -heappushpop(large, num))#将num放入大根堆,并弹出大根堆的最小值,取反,放入小根堆small
        if len(large) < len(small):
            heappush(large, -heappop(small)) #弹出small中最小的值,取反,即最大的值,放入large
        
    def GetMedian(self,ss):
        # write code here
        small,large = self.heaps
        if len(large) > len(small):
            return float(large[0])
        return (large[0] - small[0]) /2.0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章