1. 程式人生 > 實用技巧 >leetcode(36,37)-最大矩形,二叉樹中的中序遍歷

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