二叉搜索樹的第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