给定二叉搜索树,要求不使用额外空间,寻找中位数
要求
Given a BST (Binary search Tree), how
will you find median in that?
• Constraints:
• * No extra memory.
• * Function should be reentrant (No static, global
variables allowed.)
• * Median for even no of nodes will be the
average of 2 middle elements and for odd no of
terms will be middle element only.
• * Algorithm should be efficient in terms of
complexity.
代码
class BiTNode:
def __init__(self):
self.data = None
self.lchild = None
self.rchild = None
class Test:
def __init__(self):
self.pHead = None
# 双向链表头结点
self.pEnd = None
# 双向链表尾结点
# 把有序数组转换成二叉树
def array_to_tree(self, array, start, end):
root = None
if end >= start:
root = BiTNode()
mid = int((start + end + 1) / 2)
# 树的根节点为数组中间的元素
root.data = array[mid]
# 递归的用左半部分数组构造root的左子树
root.lchild = self.array_to_tree(array, start, mid - 1)
# 递归用右半部分数组构造root的右子树
root.rchild = self.array_to_tree(array, mid + 1, end)
else:
root = None
return root
# 把二叉树转换成双向列表
def tree_to_link(self, root):
if root is None:
return
# 转换root的左子树
self.tree_to_link(root.lchild)
# 使当前结点的左子树指向双向链表中的最后一个结点
root.lchild = self.pEnd
# 双向列表为空,当前遍历的结点为双向链表的头结点
if None is self.pEnd:
self.pHead = root
else:
self.pEnd.rchild = root
self.pEnd = root
self.tree_to_link(root.rchild)
def mid_BSTree(self, root):
# 中序遍历验证
if root is None:
return
self.mid_BSTree(root.lchild)
print(root.data)
self.mid_BSTree(root.rchild)
def find_mid(self, pHead, pEnd):
# 寻找中位数
print(pHead.data, pEnd.data)
if pHead == pEnd:
return
while pHead.rchild != pEnd and pHead != pEnd:
pHead, pEnd = pHead.rchild, pEnd.lchild
return (pHead.data + pEnd.data) / 2
a = Test()
ls = [0, 3, 6, 8, 9]
tree = a.array_to_tree(ls, 0, len(ls) - 1)
a.mid_BSTree(tree)
a.tree_to_link(tree)
print(a.find_mid(a.pHead, a.pEnd))