leetcode(36,37)-最大矩形,二叉树中的中序遍历

最大矩形

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例:

输入:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
输出: 6

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximal-rectangle

这道题是(34)的延伸,把矩阵变成是n 个matrix[:i,:]的矩阵,每个矩阵沿着cloumn求和就是第(34)题,求出n个中的最大就行。

class Solution:

    # Get the maximum area in a histogram given its heights
    def leetcode84(self, heights):
        stack = [-1]

        maxarea = 0
        for i in range(len(heights)):

            while stack[-1] != -1 and heights[stack[-1]] >= heights[i]:
                maxarea = max(maxarea, heights[stack.pop()] * (i - stack[-1] - 1))
            stack.append(i)

        while stack[-1] != -1:
            maxarea = max(maxarea, heights[stack.pop()] * (len(heights) - stack[-1] - 1))
        return maxarea


    def maximalRectangle(self, matrix: List[List[str]]) -> int:

        if not matrix: return 0

        maxarea = 0
        dp = [0] * len(matrix[0])
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):

                # update the state of this row's histogram using the last row's histogram
                # by keeping track of the number of consecutive ones

                dp[j] = dp[j] + 1 if matrix[i][j] == '1' else 0

            # update maxarea with the maximum area from this row's histogram
            maxarea = max(maxarea, self.leetcode84(dp))
        return maxarea

中序遍历

给定一个二叉树,返回它的中序 遍历。
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

class Solution:
    def inorderTraversal(self, root: TreeNode):
        stack = []
        if root is None: return []
        stack.append((1,root))
        ans = []
        while len(stack)>0:
            flag, top = stack.pop()

            if flag == 1:
                if top.left is None:
                    stack.append((0,top))
                else:
                    stack.append((0,top))
                    stack.append((1,top.left))
            elif flag == 0:
                ans.append(top.val)
                if top.right is None:
                    pass
                else:
                    stack.append((1,top.right))
        return ans
posted @ 2020-09-18 17:24  木子士心王大可  阅读(114)  评论(0)    收藏  举报