搜索二叉树转换双向链表寻找中位数python实现

给定二叉搜索树,要求不使用额外空间,寻找中位数

要求

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))
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值