程序员代码面试指南 python实现(第一章 栈和队列 :构造数组的MaxTree)

程序员代码面试指南 python实现(构造数组的MaxTree)

程序员代码面试指南 python实现(第一章 栈和队列)

构造数组的MaxTree

题目描述
在这里插入图片描述

分析
在这里插入图片描述

class Stack(object):
    def __init__(self):
        self.item = []

    def isEmpty(self):
        return self.item == []

    def push(self,newElem):
        self.item.append(newElem)

    def pop(self):
        if self.isEmpty():
            raise Exception("Your stack is empty!")
        else:
            return self.item.pop()

    def peek(self):
        if self.isEmpty():
            raise Exception("Your stack is Empty!")

        else:
            return self.item[len(self.item)-1]

    def size(self):
        return len(self.item)

class TreeNode(object):
    def __init__(self,data):
        self.value = data
        self.left = None
        self.right = None

def popStackSetMap(stack,map):

    popNode = stack.pop()

    if stack.isEmpty():
        map[popNode] = None
    else:
        map[popNode] = stack.peek()




def getMaxTree(arr):
    nArr = []
    for i in arr:
        nArr.append(TreeNode(i))


    stack = Stack()
    lBigMap = {}
    rBigMap = {}
    for i in nArr:
        curNode = i
        while stack.isEmpty() != True and stack.peek().value < curNode.value:
            popStackSetMap(stack,lBigMap)
        stack.push(curNode)

    while stack.isEmpty() != True:
        popStackSetMap(stack,lBigMap)


    for i in reversed(nArr):
        curNode = i

        while stack.isEmpty() != True and stack.peek().value < curNode.value:
            popStackSetMap(stack,rBigMap)
        stack.push(curNode)
    while stack.isEmpty() != True:
        popStackSetMap(stack,rBigMap)
    head =None

    for i in nArr:
        curNode = i

        left = lBigMap[i]
        right = rBigMap[i]
        if left == None and right == None:
            head = curNode
        elif left == None:
            if right.left == None:
                right.left = curNode
            else:
                right.right = curNode
        elif right == None:
            if left.left == None:
                left.left = curNode
            else:
                left.right = curNode
        else:
            if left.value < right.value:
                parent = left
            else:
                parent = right

            if parent.left == None:
                parent.left = curNode
            else:
                parent.right = curNode

    return head

if __name__ == "__main__":
    arr = [3,4,5,1,2]
    print(getMaxTree(arr).value)




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值